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

我是研究僧i 提交于 2021-02-07 05:02:49

问题


The below code works perfectly for python 2.7.13

import os
with open('random.bin','w') as f:
    f.write(os.urandom(10))

But throws error for python 3 3.6.0 |Anaconda 4.3.0 (64-bit)| (default, Dec 23 2016, 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

Any reason why there is difference in behaviour or how to fix this


回答1:


In Python 3 it makes a difference whether you open the file in binary or text mode. Just add the b flag to make it binary:

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

This works in Python 2 too.



来源:https://stackoverflow.com/questions/47027254/typeerror-write-argument-must-be-str-not-bytes-python-3-vs-python-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!