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')就可以完美解决问题。

  • 24
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
这个错误提示意味着在Python中,列表的索引必须是整数或者切片对象,而不能是字符串。 通常出现这个错误的原因是,当你尝试使用字符串作为索引来访问一个列表的元素时,Python会报错。来访问列表中的第一个元素。如果你想使用字符串作为索引,你可以将列表转换成字典,并使用字符串作为键来访问对应的值。 总结起来,为了解决这个错误,你需要确保使用整数或者切片对象作为列表的索引,或者考虑使用字典来替代列表,以便能够使用字符串作为索引来访问元素。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [PythonTypeError: list indices must be integers or slices, not str报错解决及原理](https://blog.csdn.net/hhd1988/article/details/128031602)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [python列表报错TypeError: list indices must be integers or slices, not str](https://blog.csdn.net/qq_55187385/article/details/125835936)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值