【发布时间】:2013-06-17 23:56:12
【问题描述】:
这是一个有点奇怪的请求,但我正在寻找一种将列表写入文件然后在其他时间读回的方法。
我无法重新制作列表,以便它们的格式/格式正确,如下例所示。
我的列表有如下数据:
test
data
here
this
is one
group :)
test
data
here
this
is another
group :)
【问题讨论】:
标签: python file list python-2.7 save
这是一个有点奇怪的请求,但我正在寻找一种将列表写入文件然后在其他时间读回的方法。
我无法重新制作列表,以便它们的格式/格式正确,如下例所示。
我的列表有如下数据:
test
data
here
this
is one
group :)
test
data
here
this
is another
group :)
【问题讨论】:
标签: python file list python-2.7 save
如果您不需要它是人类可读/可编辑的,最简单的解决方案就是使用pickle。
写作:
with open(the_filename, 'wb') as f:
pickle.dump(my_list, f)
阅读:
with open(the_filename, 'rb') as f:
my_list = pickle.load(f)
如果您确实需要它们可读,我们需要更多信息。
如果my_list 保证是一个没有嵌入换行符的字符串列表,只需每行写一个:
with open(the_filename, 'w') as f:
for s in my_list:
f.write(s + '\n')
with open(the_filename, 'r') as f:
my_list = [line.rstrip('\n') for line in f]
如果它们是 Unicode 字符串而不是字节字符串,您需要 encode 它们。 (或者,更糟糕的是,如果它们是字节字符串,但不一定与系统默认的编码相同。)
如果它们可能有换行符或不可打印的字符等,您可以使用转义或引用。 Python 在标准库中内置了多种不同类型的转义。
让我们在这里使用unicode-escape同时解决以上两个问题:
with open(the_filename, 'w') as f:
for s in my_list:
f.write((s + u'\n').encode('unicode-escape'))
with open(the_filename, 'r') as f:
my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]
您还可以在 2.x 中使用 3.x 样式的解决方案,与 codecs 模块或 io 模块一起使用:*
import io
with io.open(the_filename, 'w', encoding='unicode-escape') as f:
f.writelines(line + u'\n' for line in my_list)
with open(the_filename, 'r') as f:
my_list = [line.rstrip(u'\n') for line in f]
* TOOWTDI,那么哪一种是显而易见的方式?这取决于... 对于简短版本:如果您需要使用 2.6 之前的 Python 版本,请使用 codecs;如果没有,请使用io。
【讨论】:
str 和 bytes 是同一类型,二进制文件和文本文件之间的区别只是换行符翻译。在 Python 3 中,str 和 unicode 是同一种类型,二进制文件和文本文件的区别在于文本文件会自动为你编码和解码。 (如果你小心点的话,如果是 2.x,你可以得到类似 3.x 的行为,包括带有 io.open 的 3.x 样式的文本文件,但提问者没有这样做。)
open(the_filename, 'w', encoding='unicode-escape') 并让文件对象负责为您编码。 (你可以在 2.x 中使用 io.open 或 codecs 模块做同样的事情,但我认为显式编码可以更容易地看到 2.x 中发生了什么,其中混合字节和文本的危险很大更高。)
\n。将 f.write((s + u'\n').encode('unicode-escape')) 更改为 f.write(s.encode('unicode-escape') + u'\n') 可以解决此问题。
只要您的文件具有一致的格式(即换行符),只需基本的文件 IO 和字符串操作即可轻松完成:
with open('my_file.txt', 'rU') as in_file:
data = in_file.read().split('\n')
这会将您的数据文件存储为项目列表,每行一个。然后将其放入文件中,您将执行相反的操作:
with open('new_file.txt', 'w') as out_file:
out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters
希望这符合您的要求。
【讨论】:
data 并不复杂,恕我直言,最好在这个答案中滚动您自己的解析器。
让我们先定义一个列表:
lst=[1,2,3]
您可以直接将列表写入文件:
f=open("filename.txt","w")
f.write(str(lst))
f.close()
要从文本文件中读取您的列表,首先您读取文件并将其存储在变量中:
f=open("filename.txt","r")
lst=f.read()
f.close()
变量lst的类型当然是字符串。您可以使用eval 函数将此字符串转换为数组。
lst=eval(lst)
【讨论】: