繁体   English   中英

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

[英]TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 )

下面的代码适用于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)]

回溯(最近调用最后一次):文件“C:/Users/hsingh/Py​​charmProjects/Item3.py”,第3行,在f.write中(os.urandom(10))TypeError:write()参数必须是str,不是字节

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

在Python 3中,无论是以二进制还是文本模式打开文件,都会有所不同。 只需添加b标志即可使其成为二进制:

with open('random.bin','wb') as f:

这也适用于Python 2。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM