如何挑选清单?[已关闭]

问题描述 投票:57回答:1

我想保存一个列表,只包含字符串,以便以后可以访问。有人告诉我使用pickling。我希望有一个例子。

python list pickle
1个回答
119
投票

Pickling会将你的列表序列化(将它和它的条目转换为一个唯一的字节字符串),所以你可以将它保存到磁盘上。 你也可以使用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."]
>>>
© www.soinside.com 2019 - 2024. All rights reserved.