我有一个字符串列表,其中一些字符串包含'\n'。我想将这个字符串列表写入文本文件,然后使用 readlines() 将其读回并存储到列表中。我必须保留原文;意思是不从文本中删除新行。
如果我不删除所有这些新行,那么 readlines() 将返回比原始列表更多的字符串。
我怎样才能做到这一点?或者真的没办法,我应该改用其他格式来写。谢谢。
请您参考如下方法:
以下内容:
from __future__ import print_function
strings = ["asd", "sdf\n", "dfg"]
with open("output.txt", "w") as out_file:
for string in strings:
print(repr(string), file=out_file)
with open("output.txt") as in_file:
for line in in_file:
print(line.strip())
打印
'asd'
'sdf\n'
'dfg'
要正常打印(不带引号),您可以使用 ast.literal_eval : print(ast.literal_eval(line.strip()))
