将列表保存到pickle文件中并稍后检索
我想保存一个字符串列表,以便以后可以访问。请问怎么用pickle来实现呢?如果能给个例子就更好了。
1 个回答
259
把列表进行“打包”会把它和里面的内容转换成一种独特的字节串,这样你就可以把它保存到硬盘上。你也可以用这个“打包”功能来恢复你原来的列表,从保存的文件中加载出来。
所以,首先你要创建一个列表,然后用 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."]
>>>