Python3.x下pickle模块的注意点
2012年1月11日 16:24
公司win xp机器上的Python环境是3.0v的。
学Python的文件操作部分,对于Python对象持久化,
Python自带有一个pickle模块,用于把Python的对象(包括内置类型和自定义类型)
写入到文件中。
在learning Python书中的示例是通过
1 2 3 4 5 | import pickle D = { 1 : 1 , 2 : 2 } F = open ( 'file.txt' , 'w' ) pickle.dump(D, F) F.close() |
但是在个人的环境中做实验时,出现如下异常
TypeError: can't write bytes to text stream
通过Google查,有人说因为Python3中做了修改,
所以应该使用下列方式打开文件
F = open ( 'file.txt' , 'wb' ) |
给出的原因是:“因为存储的是对象,必须使用二进制形式写进文件。”
那么也就顺便查了一下文档。
“The file argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface”
这也就是说明了,如果想要通过pickle模块去持久化Python的对象,那么需要以二进制的方式写入/读取文档。