Python:将元组列表写入文件

时间:2010-09-29 09:30:08

标签: python

如何编写以下列表:

[(8, 'rfa'), (8, 'acc-raid'), (7, 'rapidbase'), (7, 'rcts'), (7, 'tve-announce'), (5, 'mysql-im'), (5, 'telnetcpcd'), (5, 'etftp'), (5, 'http-alt')]

到一个包含两列(8 rfa)和多行的文本文件,以便我有这样的内容:

8 rfa
8 acc-raid
7 rapidbase
7 rcts
7 tve-announce
5 mysql-im
5 telnetcpcd 

提前致谢

6 个答案:

答案 0 :(得分:44)

with open('daemons.txt', 'w') as fp:
    fp.write('\n'.join('%s %s' % x for x in mylist))

如果要使用str.format(),请将第二行替换为:

    fp.write('\n'.join('{} {}'.format(x[0],x[1]) for x in mylist)

答案 1 :(得分:21)

import csv
with open(<path-to-file>, "w") as the_file:
    csv.register_dialect("custom", delimiter=" ", skipinitialspace=True)
    writer = csv.writer(the_file, dialect="custom")
    for tup in tuples:
        writer.write(tup)

csv模块非常强大!

答案 2 :(得分:5)

open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))

答案 3 :(得分:1)

谢谢你们。这是我提出的第三种方式:

for number, letter in myList:
    of.write("\n".join(["%s %s" % (number, letter)]) + "\n")

答案 4 :(得分:1)

使用str()

将元组简单地转换为字符串
f=open("filename.txt","w+")
# in between code
f.write(str(tuple)+'/n')
# continue

答案 5 :(得分:0)

例如,出于灵活性考虑;如果列表中的某些项目包含3个项目,其他项目包含4个项目,而其他项目包含2个项目,则可以执行此操作。

mylst = [(8, 'rfa'), (8, 'acc-raid','thrd-item'), (7, 'rapidbase','thrd-item','fourth-item'),(9, 'tryrt')]

# this function converts the integers to strings with a space at the end
def arrtostr(item):
    strr=''
    for b in item:
        strr+=str(b)+'   '
    return strr

# now write to your file
with open('list.txt','w+') as doc:
    for line in mylst:
        doc.write(arrtostr(line)+'\n')
    doc.close()

以及list.txt中的输出

8   rfa   
8   acc-raid   thrd-item   
7   rapidbase   thrd-item   fourth-item   
9   tryrt