Python 如何腌制一个列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25464295/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:14:52  来源:igfitidea点击:

How to pickle a list?

pythonlistpickle

提问by Lewis

I'm trying to save a list, only containing strings, so it can be accessed later. Someone told me to use pickling. I was hoping for an example.

我正在尝试保存一个仅包含字符串的列表,以便以后可以访问它。有人告诉我使用酸洗。我希望有一个例子。

采纳答案by Mike McKerns

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

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

So, first build a list, then use pickle.dumpto send it to a file...

所以,首先建立一个列表,然后使用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)
... 
>>> 

Then quit and come back later… and open with pickle.load...

然后退出并稍后回来......并打开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."]
>>>