将列表导出为 .txt (Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2308883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Export list as .txt (Python)
提问by eozzy
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:
我的 Python 模块有一个列表,其中包含我想在某处另存为 .txt 文件的所有数据。该列表包含几个元组,如下所示:
list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
How do I print the list so each tuple item is separated by a tab and each tuple is separated by a newline?
如何打印列表,以便每个元组项目由制表符分隔,每个元组由换行符分隔?
Thanks
谢谢
回答by Anurag Uniyal
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
您可以解决它,正如其他答案所建议的那样,只需加入行,但更好的方法是仅使用 python csv 模块,以便稍后您可以轻松更改分隔符或添加标题等并将其读回,看起来您想要制表符分隔文件
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
回答by Ignacio Vazquez-Abrams
print '\n'.join('\t'.join(x) for x in L)
回答by YOU
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
>>>
回答by Matt Joiner
open("data.txt", "w").write("\n".join(("\t".join(item)) for item in list))
回答by tim.tadh
The most idiomatic way, IMHO, is to use a list comprehension and a join:
恕我直言,最惯用的方法是使用列表理解和连接:
print '\n'.join('\t'.join(i) for i in l)
回答by tzot
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)