7.2.2 pickle 模块 pickle Module

Strings can easily be written to and read from a file. Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int(), which takes a string like '123' and returns its numeric value 123. However, when you want to save more complex data types like lists, dictionaries, or class instances, things get a lot more complicated.

我们可以很容易的读写文件中的字符串。数值就要多费点儿周折,因为 read() 方法只会返回字符串,应该将其传入 int() 方法中,就可以将 '123' 这样的字符转为对应的数值123。不过,当你需要保存更为复杂的数据类型,例如链表、字典,类的实例,事情就会变得更复杂了。

Rather than have users be constantly writing and debugging code to save complicated data types, Python provides a standard module called pickle. This is an amazing module that can take almost any Python object (even some forms of Python code!), and convert it to a string representation; this process is called pickling. Reconstructing the object from the string representation is called unpickling. Between pickling and unpickling, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.

好在用户不必要非得自己编写和调试保存复杂数据类型的代码。Python 提供了一个名为 pickle 的标准模块。这是一个令人赞叹的模块,几乎可以把任何 Python 对象(甚至是一些 Python 代码块( form )!) 表达为为字符串,这一过程称之为封装pickling )。从字符串表达出重新构造对象称之为拆封unpickling )。封装状态中的对象可以存储在文件或对象中,也可以通过网络在远程的机器之间传输。

If you have an object x, and a file object f that's been opened for writing, the simplest way to pickle the object takes only one line of code:

如果你有一个对象 x ,一个以写模式打开的文件对象 f ,封装对像的最简单的方法只需要一行代码:

pickle.dump(x, f)

To unpickle the object again, if f is a file object which has been opened for reading:

如果 f 是一个以读模式打开的文件对象,就可以重装拆封这个对象:

x = pickle.load(f)

(There are other variants of this, used when pickling many objects or when you don't want to write the pickled data to a file; consult the complete documentation for pickle in the Python Library Reference.)

(如果不想把封装的数据写入文件,这里还有一些其它的变化可用。完整的 pickle 文档请见Python 库参考手册)。

pickle is the standard way to make Python objects which can be stored and reused by other programs or by a future invocation of the same program; the technical term for this is a persistent object. Because pickle is so widely used, many authors who write Python extensions take care to ensure that new data types such as matrices can be properly pickled and unpickled.

pickle 是存储 Python 对象以供其它程序或其本身以后调用的标准方法。提供这一组技术的是一个持久化对象( persistent object )。因为 pickle 的用途很广泛,很多 Python 扩展的作者都非常注意类似矩阵这样的新数据类型是否适合封装和拆封。