Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 276
Hariom Singh Avatar asked Oct 31 '17 03:10

Hariom Singh


People also ask

Can only concatenate str not bytes to str?

The Python "TypeError: can only concatenate str (not "bytes") to str" occurs when we try to concatenate a string and a bytes object. To solve the error, decode the bytes object into a string before concatenating the strings.


1 Answers

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.

like image 54
Mark Ransom Avatar answered Oct 01 '22 01:10

Mark Ransom