Search code examples
pythoncsvwriter

Two Tab-Separated Delimiter in Python Writing to TSV


I have the following code:

f = open("test.tsv", 'wt')
try:
    writer = csv.writer(f, delimiter='\t')
    for x in range(0, len(ordered)):
        writer.writerow((ordered[x][0],"\t", ordered[x][1]))
finally:
    f.close()

I need the TSV file to have the ordered[x][0] separated by two tabs with ordered[x][1] the "\t" adds space, but its not a tab and the parentheses are shown on the output.

Thank You!


Solution

  • You could replace the "\t" by "" to obtain what you want:

    writer.writerow((ordered[x][0],"", ordered[x][1]))
    

    Indeed, the empty string in the middle will then be surrounded by a tab on both sides, effectively putting two tabs between ordered[x][0] and ordered[x][1].

    However, a more natural code doing exactly the same thing would be:

    with open("test.tsv", "w") as fh:
        for e in ordered:
            fh.write("\t\t".join(map(str, e[:2])) + "\n")
    

    where I:

    • used a with statement (explained here) instead of the try ... finally construct
    • removed the t mode in the open function (t is the default behavior)
    • iterated over the elements in ordered using for ... in instead of using an index
    • used join instead of a csv writer: those are suited in cases where the delimiter is a single character