将列表转储到pickle文件中,以后再取回[关闭]


80

我正在尝试保存字符串列表,以便以后可以访问。如何使用泡菜来实现?一个说明性的例子可能会有所帮助。



2
列表包含什么?
Ry-

4
然后json是重量更轻的选项。
马丁·皮特斯

11
我不明白为什么这个问题已经解决。这是一个简单的Python编程问题。这个问题及其公认的答案提供了一个非常快速的基于Google搜索的答案,它回答了许多程序员在日常工作中需要知道的简单问题。
Dan Nissenbaum

1
我编辑了该问题,以删除我怀疑导致该问题被关闭的问题中的(第二条)注释。
Dan Nissenbaum

Answers:


138

腌制将序列化您的列表(将其转换为一个唯一的字节字符串,并将其输入),因此您可以将其保存到磁盘。您还可以使用pickle检索原始列表,从保存的文件中加载。

因此,首先建立一个列表,然后使用pickle.dump将其发送到文件...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

然后退出,然后再回来...并打开pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

42
在那串字符串中,这是一个沉重的故事迈克...还是谢谢你!
Leogout

如果该列表对于您的内存来说太大了,该怎么办?您不想一次将整个列表读入内存,而是一次只想读取一部分列表。是否可以通过pickle将部分列表读取到内存中?
瓦特(Watt)

@Watt:如果将其腌制为列表,则不会。如果列表已转换为可以大步读取的内容,则可以。
Mike McKerns
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.