Python:将元组列表写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3820312/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:54:14  来源:igfitidea点击:

Python: Write a list of tuples to a file

python

提问by Adia

How can I write the following list:

我该如何编写以下列表:

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

to a text file with two columns (8 rfa)and many rows, so that I have something like this:

到一个有两列(8 rfa)多行的文本文件,所以我有这样的东西:

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

采纳答案by Ignacio Vazquez-Abrams

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

If you want to use str.format(), replace 2nd line with:

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

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

回答by Katriel

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)

The csvmodule is very powerful!

csv模块是非常强大的!

回答by Adia

Here is the third way that I came up with:

这是我想出的第三种方法:

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

回答by stan

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

回答by Rohit Sohlot

simply convert the tuple to string with str()

只需将元组转换为字符串 str()

f=open("filename.txt","w+")
# in between code
f.write(str(tuple)+'/n')
# continue

回答by leon koech

For flexibility, for example; if some items in your list contain 3 items, others contain 4 items and others contain 2 items you can do this.

例如,为了灵活性;如果您列表中的某些项目包含 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()

And the output in list.txt

和 list.txt 中的输出

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