Python 提示TypeError: write() argument must be str, not bytes

在自己敲机器学习实战(Machine Learning in Action)决策树一章的代码时,准备将构造的树存储及读取时出现

pickle.dump(inputTree, fw)
TypeError: write() argument must be str, not bytes

看着提示信息是说write()参数必须是字符,不能是字节。粗看不知道是什么意思。打开源代码后发现以下几段描述:

The optional *protocol* argument tells the pickler to use the
given protocol; supported protocols are 0, 1, 2, 3 and 4.  The
default protocol is 3; a backward-incompatible protocol designed
for Python 3.

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, an 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 names to the old module names
used in Python 2, so that the pickle data stream is readable
with Python 2.

               

从到数第二段的内容可以发现,这个函数要求读写文件以二进制读写,因此只要将定义的两个函数中(上图中蓝色标记的地方)fw=open(filename,'w')和fr=open(filename,‘r’)改为fw=open(filename,‘wb’)和fr=open(filename,‘rb')就可以完美解决问题。

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值