加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

TypeError:write()参数必须是str,而不是字节(Python 3 vs Pytho

发布时间:2020-12-16 21:29:44 所属栏目:Python 来源:网络整理
导读:下面的代码适用于 python 2.7.13 import oswith open('random.bin','w') as f: f.write(os.urandom(10)) 但抛出python 3的错误 3.6.0 | Anaconda 4.3.0(64位)| (默认,2016年12月23日,11:57:41)[MSC v.1900 64 bit(AMD64)] Traceback (most recent call las
下面的代码适用于 python 2.7.13
import os
with open('random.bin','w') as f:
    f.write(os.urandom(10))

但抛出python 3的错误
3.6.0 | Anaconda 4.3.0(64位)| (默认,2016年12月23日,11:57:41)[MSC v.1900 64 bit(AMD64)]

Traceback (most recent call last): File
“C:/Users/hsingh/PycharmProjects/Item3.py”,line 3,in

f.write(os.urandom(10)) TypeError: write() argument must be str,not bytes

行为不同或如何解决这个问题的原因

解决方法

在Python 3中,无论是以二进制还是文本模式打开文件,都会有所不同.只需添加b标志即可使其成为二进制:
with open('random.bin','wb') as f:

这也适用于Python 2.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读