问题描述
这是一个稍微奇怪的请求,但我正在寻找一种方法来写一个列表到文件,然后再读一次。
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]
您还可以使用2.x中的3.x样式解决方案,其中包含模块或模块:*
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]
这篇关于Python 2.7 - 从文件中读取和读取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!