简体   繁体   English

Python:将元组列表写入文件

[英]Python: Write a list of tuples to a file

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 
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)
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 csv module is very powerful!csv模块非常强大!

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

Here is the third way that I came up with:这是我想出的第三种方法:

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

simply convert the tuple to string with str()只需使用str()将元组转换为字符串

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

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  

After adding f-strings in Python you can use this example:在 Python 中添加 f 字符串后,您可以使用此示例:

mylst = [(8, 'rfa'), (8, 'acc-raid'), (7, 'rapidbase'), (7, 'rcts'), (7, 'tve-announce'), (5, 'mysql-im')]
f = open('out.txt', mode='w+')
for elem in mylst:
    f.write(f'{elem}\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM