从文件中写入和读取列表

Ryf*_*lex 36 python file list save python-2.7

这是一个有点奇怪的请求,但我正在寻找一种方法将列表写入文件,然后在其他时间读回.

我没有办法重新制作列表,以便正确形成/格式化它们,如下例所示.

我的列表包含以下数据:

test
data
here
this
is one
group :)

test
data
here
this
is another
group :)
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 101

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)
Run Code Online (Sandbox Code Playgroud)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)
Run Code Online (Sandbox Code Playgroud)

If you do need them to be human-readable, we need more information.

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]
Run Code Online (Sandbox Code Playgroud)

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中内置了各种不同类型的转义.

让我们一起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]
Run Code Online (Sandbox Code Playgroud)

您还可以在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]
Run Code Online (Sandbox Code Playgroud)

*TOOWTDI,这是一个显而易见的方法吗?这取决于...对于简短版本:如果您需要在2.6之前使用Python版本,请使用codecs; 如果没有,请使用io.


Der*_*son 13

只要您的文件具有一致的格式(即换行符),只需基本的文件IO和字符串操作就可以轻松实现:

with open('my_file.txt', 'rU') as in_file:
    data = in_file.read().split('\n')
Run Code Online (Sandbox Code Playgroud)

这会将您的数据文件存储为项目列表,每行一个.然后把它放到一个文件中,你会做相反的事情:

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
Run Code Online (Sandbox Code Playgroud)

希望这符合您的需求.


Ali*_*ürk 6

我们先定义一个列表:

lst=[1,2,3]
Run Code Online (Sandbox Code Playgroud)

您可以直接将列表写入文件:

f=open("filename.txt","w")
f.write(str(lst))
f.close()
Run Code Online (Sandbox Code Playgroud)

要从文本文件读取列表,首先要读取该文件并将其存储在变量中:

f=open("filename.txt","r")
lst=f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)

变量的类型lst当然是字符串。您可以使用函数将此字符串转换为数组eval

f=open("filename.txt","r")
lst=f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)