19
votes

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
f.write(str(os.urandom(10))) works for me - JacobIRR
@JacobIRR which version of python you are using? - Hariom Singh
>>> sys.version '3.6.1...' - JacobIRR
Same error I got in online compiler rextester.com/l/python3_online_compiler - Hariom Singh
I'm sure you'll find plenty of ways to fix this by googling "python write bytes to file" - jonatan

1 Answers

36
votes

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.