python 3.1 兼容问题一则:pickle 操作时文件读写模式
时间:2010-06-27 来源:jiusuihe
python 3升级变化颇多,这些天遇到不少,比如 pickle:
import pickle
shoplist = ['apple','food','noodle']
f = open('temp1.txt','wb')
pickle.dump(shoplist,f)
f.close()
f = open('temp1.txt','rb')
print(pickle.load(f))
f.close()
初始调试的时候,按照习惯设置打开模式为‘w’或者‘r’,报错:
Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
TypeError: must be str, not bytes
搜索老外论坛得到原因:
For one thing, don't name your list "list", as that's a reserved word in Python (try list('12345') ), same thing with file... But that modification won't help you.
I'm assuming you've got a new version of Python installed, as the method you're using will only work in earlier versions of python.
•
•
•
•
pickle.dump(obj, file[, protocol, *, fix_imports=True])¶
Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj).
The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3. The default protocol is 3; a backward-incompatible protocol designed for Python 3.0.
Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced.
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.
If fix_imports is True and protocol is less than 3, pickle will try to map the new Python 3.x names to the old module names used in Python 2.x, so that the pickle data stream is readable with Python 2.x.
That's from the 3.1 docs; note that you must open your files in binary mode now. So for dumping use 'wb', and loading use 'rb'.
原来python 3以后必须使用模式‘wb’和‘rb’(load时)。