简体   繁体   中英

Python Write lists in a file

My question is: How can I write lists in a file?

So:

list = ["damn","bro"]
correct_list = "\n".join(list)
file = open("test.txt", "w")

How do I write this into a file now that it's a list? So in the file:

damn
bro

I already tried it but it just stand behind each other without whitespace

First, you probably shouldn't use list because it is a reserved word in python.( link ) You could use almost anything else. I usually use lst

You need to actually put it in the file. Your code is missing:

file.write(correct_list)

this will actually write the string to the file.

You can also try something like this:

lst=["damn","bro"]
file = open("test.txt", "w")
for item in lst:
    file.write(item+"\n")

This will loop over each item in the list and write them one at a time to the file with a new line at the end

Also make sure you close the file when you are done with it:

file.close()

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