从文件写入和读取列表 [英] Write and read a list from file
问题描述
这是一个有点奇怪的请求,但我正在寻找一种方法来将列表写入文件,然后再读回去.
This is a slightly weird request but I am looking for a way to write a list to file and then read it back some other time.
我无法重新制作列表,以使它们如以下示例所示正确地形成/格式化.
I have no way to remake the lists so that they are correctly formed/formatted as the example below shows.
我的列表中的数据如下:
My lists have data like the following:
test
data
here
this
is one
group :)
test
data
here
this
is another
group :)
推荐答案
如果您不需要它是人类可读/可编辑的,则最简单的解决方案是只使用pickle
.
If you don't need it to be human-readable/editable, the easiest solution is to just use 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)
如果您要做需要它们易于阅读,我们需要更多信息.
If you do need them to be human-readable, we need more information.
如果保证my_list
是一个没有嵌入换行符的字符串列表,只需每行写一个即可:
If my_list
is guaranteed to be a list of strings with no embedded newlines, just write them one per line:
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
. (或者,更糟糕的是,如果它们是字节字符串,但不一定采用与系统默认设置相同的编码.)
If they're Unicode strings rather than byte strings, you'll want to encode
them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)
如果它们可能包含换行符或不可打印的字符等,则可以使用转义或引号. Python在stdlib中内置了各种不同的转义.
If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.
让我们在这里使用unicode-escape
一次解决上述两个问题:
Let's use unicode-escape
here to solve both of the above problems at once:
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]
You can also use the 3.x-style solution in 2.x, with either the codecs
module or the io
module:*
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
;否则,请使用codecs
.如果没有,请使用io
.
* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs
; if not, use io
.
这篇关于从文件写入和读取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!