将列表导出为.txt(Python)

2024-04-25 23:33:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python模块有一个列表,其中包含了我想保存为.txt文件的所有数据。列表包含几个元组,如下所示:

list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]

如何打印列表,使每个元组项由制表符分隔,每个元组由换行符分隔?

谢谢


Tags: 模块文件数据txt列表one制表符list
3条回答
print '\n'.join('\t'.join(x) for x in L)

试试这个

"\n".join(map("\t".join,l))

测试

>>> l = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
>>> print "\n".join(map("\t".join,l))
one     two     three
four    five    six
>>>

正如其他答案所建议的那样,您可以通过连接行来解决这个问题,但更好的方法是只使用python csv模块,这样以后您就可以轻松地更改delimter或添加header等并将其读回,看起来您需要用制表符分隔的文件

import sys
import csv

csv_writer = csv.writer(sys.stdout, delimiter='\t')
rows = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
csv_writer.writerows(rows)

输出:

one two three
four    five    six

相关问题 更多 >