简体   繁体   中英

How do I read and write a list of strings to a file in python 3?

I have tried some ways but they either don't work or turn out to be a letter for each item in the list. For example, this (for writing the list):

with open("data.txt", 'w') as f:
    for s in data:
        f.write(s + '\n')

and this (for reading the list):

try:
    with open("data.txt", 'r') as f:
        data = [Line.rstrip('\n') for Line in f]
except FileNotFoundError:
    print ("There is nothing to show")
else:
    print (data) 

Prints out this when the list I want in the file is "['Bob:6', 'Dave:4']" :

['B', 'o', 'b', ':', '6', 'D', 'a', 'v', 'e', ':', '4'] 

Basically, I want it to be readable properly, with the different values separated properly.

What is "data" in your writing snippet? I'd guess it's a string not a list, and therefore iterating over it is writing one character per line, rather than one property per line.

Open the text file in an editor to be sure you are writing it correctly ...

Your have written you data as a column of chars, and it is written back as a char each time Apparently you data was data one line when you written is into the file.

 **for s in data**

 --- if you data is just one line, it will be written as a column...

so I think you have written Bob:6', 'Dave:4' to file, 

as a column of single chars You have should change your data from string to list. Just put that data string into a list, with data = list(data) and try writing and reading again. All should go well.

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