繁体   English   中英

Python 如何将带有字符串和整数的列表打印到文本文件中

[英]Python How can I print a list with strings and intergers to a text file

这是我的清单

[('Doctor', 1), ('Paramedic', 2), ('Janitor', 3)]

我想将列表打印到文本文件中,看起来像这样,

('Doctor', 1), ('Paramedic', 2), ('Janitor', 3)

或类似的东西。

谢谢。

最简单的方法是convert list to string并使用slicing remove parenthesis并将write it to file

不需要任何loop

a = [('Doctor', 1), ('Paramedic', 2), ('Janitor', 3)]
a = str(a)[1:-1]
f = open("demofile2.txt", "a")
f.write(str(a))
f.close()

这是一个可能的解决方案:

LST = [('Doctor', 1), ('Paramedic', 2), ('Janitor', 3)]
OUTPUTFILE = "out.txt" # text file path

with open(OUTPUTFILE, "w") as f:
    for name, count in LST:
        f.write(f"{name}: {count}\n")            
some_list = [('Doctor', 1), ('Paramedic', 2), ('Janitor', 3)] with open('file.txt', 'w') as file: for item in some_list: file.write(f'{item}, ')

暂无
暂无

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

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