首先,当您需要将列表存储在文件中时,请使用 JSON、pickle 或等效项。 JSON 更适合用于长期存储以及旨在由其他程序读取或通过网络发送的存储:
import json
my_list = ["hello", "world"]
with open('file.txt', 'w') as f:
json.dump(my_list, f)
或者,如果您只想以纯文本格式每行存储一个单词/句子/短语:
my_list = ["hello", "world"]
with open('file.txt', 'w') as f:
f.write('\n'.join(my_list)) # assuming your list isn't large
f.write('\n')
(另一方面,酸洗适用于临时/内部存储,以及存储无法转换为 JSON 可以处理的形式的内容;有关更多信息,请查找 pickle 模块的文档.)
现在,如果您搞砸了,只是将列表的字符串表示形式放入文件中,您可以手动清理它,或者使用以下帮助程序:
import ast
import json
with open('file.txt') as f:
contents = f.read()
contents = ast.literal_eval(contents) # parses the string as if it were a Pytnon literal (which it is)
with open('file.txt', 'w') as f:
json.dump(contents, f) # write back as JSON this time
如果您的文件包含多个列表,每个列表位于单独的行中,您可以使用:
import ast
import json
with open('file.txt') as f:
lines = f.read().split('\n')
contents = [ast.literal_eval(line) for line in lines]
# ...and now choose from above how you'd like to write it back to the file
注意:哦,而且...这似乎与 pyscripter 无关,除非我错过了什么。