简体   繁体   English

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

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

Here is my list这是我的清单

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

I want to print the list to a text file so it will look like this,我想将列表打印到文本文件中,看起来像这样,

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

or something similar.或类似的东西。

Thanks.谢谢。

simplest way to do it is to convert list to string and remove parenthesis using slicing and write it to file最简单的方法是convert list to string并使用slicing remove parenthesis并将write it to file

No need of any loop不需要任何loop

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

here is a possible solution:这是一个可能的解决方案:

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