简体   繁体   English

如何在python 3中读写字符串列表到文件?

[英]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']" : 当我要在文件中的列表为“ ['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. 您已将数据写为char列,并且每次将其写回char时。显然,当您将数据写到文件中时,数据就是一行数据。

 **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. 只需将数据字符串放入列表中,并使用data = list(data)并尝试再次写入和读取即可。 All should go well. 一切应该顺利。

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

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