发布于 2018-02-24 08:26:56 | 146 次阅读 | 评论: 0 | 来源: 网友投递
Python编程语言
Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。
本文研究的主要是Python使用pickle模块存储数据报错解决方法,以代码的形式展示,具体如下。
首先来了解下pickle模块
接下来我们看下Python使用pickle模块存储数据报错解决方法。
代码:
# 写入错误
TypeError: write() argument must be str, not bytes
# 读取错误
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 0: illegal multibyte sequence
解决方案:
def storeTree(inputTree, fielname):
import pickle
# 写文件时,注明 'wb'
fw = open(fielname, 'wb')
pickle.dump(inputTree, fw)
fw.close()
def grabTree(filename):
import pickle
# 读文件时,注明 'rb'
fr = open(filename, 'rb')
fr = open(filename)
return pickle.load(fr)
storeTree(myTree, 'classifierStorage.txt')
print(grabTree('classifierStorage.txt'))
输出:
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
Process finished with exit code 0
总结
以上就是本文关于Python使用pickle模块存储数据报错解决示例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!