Export list as .txt (Python)
My Python module has a list that contains all the data I want to save as a .txt file somewhere. The list contains several tuples like so:
list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
How do I print the list so each tuple ite开发者_如何学Gom is separated by a tab and each tuple is separated by a newline?
Thanks
You can solve it, as other answers suggest by just joining lines but better way would be to just use python csv module, so that later on you can easily change delimter or add header etc and read it back too, looks like you want tab delimited file
import sys
import csv
csv_writer = csv.writer(sys.stdout, delimiter='\t')
rows = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
csv_writer.writerows(rows)
output:
one two three
four five six
print '\n'.join('\t'.join(x) for x in L)
Try this
"\n".join(map("\t".join,l))
Test
>>> l = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
>>> print "\n".join(map("\t".join,l))
one two three
four five six
>>>
open("data.txt", "w").write("\n".join(("\t".join(item)) for item in list))
The most idiomatic way, IMHO, is to use a list comprehension and a join:
print '\n'.join('\t'.join(i) for i in l)
You don't have to join the list in advance:
with open("output.txt", "w") as fp:
fp.writelines('%s\n' % '\t'.join(items) for items in a_list)
精彩评论