简体   繁体   中英

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

No need of any 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}, ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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