Python 从文件中写入和读取列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17225287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write and read a list from file
提问by Ryflex
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 :)
采纳答案by abarnert
If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.
如果您不需要它是人类可读/可编辑的,最简单的解决方案是使用pickle.
To write:
来写:
with open(the_filename, 'wb') as f:
pickle.dump(my_list, f)
To read:
阅读:
with open(the_filename, 'rb') as f:
my_list = pickle.load(f)
If you doneed them to be human-readable, we need more information.
如果您确实需要它们是人类可读的,我们需要更多信息。
If my_listis guaranteed to be a list of strings with no embedded newlines, just write them one per line:
如果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]
If they're Unicode strings rather than byte strings, you'll want to encodethem. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)
如果它们是 Unicode 字符串而不是字节字符串,你会想要encode它们。(或者,更糟糕的是,如果它们是字节字符串,但不一定与您的系统默认编码相同。)
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.
如果它们可能有换行符或不可打印的字符等,您可以使用转义或引用。Python 在 stdlib 中内置了多种不同类型的转义。
Let's use unicode-escapehere to solve both of the above problems at once:
让我们用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]
You can also use the 3.x-style solution in 2.x, with either the codecsmodule or the iomodule:*
您还可以在 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, 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.
* TOOWTDI,那么哪个是明显的方法?这取决于……对于简短版本:如果您需要使用 2.6 之前的 Python 版本,请使用codecs; 如果没有,请使用io.
回答by Derek Peterson
As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:
只要您的文件具有一致的格式(即换行符),只需基本的文件 IO 和字符串操作即可轻松实现:
with open('my_file.txt', 'rU') as in_file:
data = in_file.read().split('\n')
That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:
这会将您的数据文件存储为项目列表,每行一个。然后将其放入文件中,您将执行相反的操作:
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
Hopefully that fits what you're looking for.
希望这适合您正在寻找的内容。
回答by Ali ?entürk
Let's define a list first:
让我们先定义一个列表:
lst=[1,2,3]
You can directly write your list to a file:
您可以直接将列表写入文件:
f=open("filename.txt","w")
f.write(str(lst))
f.close()
To read your list from text file first you read the file and store in a variable:
要先从文本文件中读取列表,请先读取文件并将其存储在变量中:
f=open("filename.txt","r")
lst=f.read()
f.close()
The type of variable lstis of course string. You can convert this string into array using evalfunction.
变量的类型lst当然是字符串。您可以使用eval函数将此字符串转换为数组。
lst=eval(lst)

