今天在使用python 的pickle模块对数据进行序列化时遇到了一些问题,现在讲问题和方法记录下来。
def storeTree(inputTree,filename): fw = open(filename,'w') pickle.dump(inputTree,fw) fw.close()
最开始是使用了‘w’,出现了报错 write() argument must be str, not bytes
这是因为文件打开方式不对,改为(‘wb’)
def storeTree(inputTree,filename): fw = open(filename,'wb') pickle.dump(inputTree,fw) fw.close()
这时pickle出现了乱码现象,这个可以参照博客https://www.cnblogs.com/billyzh/p/6187651.html和
http://www.cnblogs.com/pzxbc/archive/2012/03/18/2404715.html
修改为
def storeTree(inputTree,filename): fw = open(filename,'wb') pickle.dump(inputTree,fw,0) fw.close()
在读取文件是,python3的pickle.load()又出现了如下问题
def grabTree(filename): fr = open(filename) return pickle.load(fr)
报错为:a bytes-like object is required, not 'str'
修改为在open的时候要加上‘rb’
def grabTree(filename): fr = open(filename,'rb') return pickle.load(fr)