【发布时间】:2014-10-17 07:51:52
【问题描述】:
我正在尝试保存一个字符串列表,以便以后可以访问它。如何使用泡菜来实现?一个说明性的例子可能会有所帮助。
【问题讨论】:
-
如果您不关心速度和安全性,最简单的方法是
repr和eval。 -
列表包含什么?
-
列表只包含字符串
-
那么
json是更轻量级的选项。
我正在尝试保存一个字符串列表,以便以后可以访问它。如何使用泡菜来实现?一个说明性的例子可能会有所帮助。
【问题讨论】:
repr 和eval。
json 是更轻量级的选项。
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."]
>>>
【讨论】: