Leuthus Leuthus - 2 months ago 6
Python Question

write to file \t creates spaces not tabs

So, I have a list of lists and trying to write the values to a file with tab delimited;

sorted_results=[
["test1", 01],
["test2", 02],
]

with open('outfile.txt', 'a') as write_file:
for i in sorted_results:
write_file.write("{}\t{}\n".format(i[0], i[1]))


The end result comes out as:

test1 01
test2 02


Values are space delimited not tab. What am I missing? If I add a space before
\t
then end result will have a space and a tab between the values.

Answer

You can read the file back in and inspect the resulting data.

>>> open('outfile.txt').read()
'test1\t1\ntest2\t2\n'

This shows that the tab character is indeed written to the file. If you are still in doubt use a hex editor to view the characters.