24

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

6
  • f.write(str(os.urandom(10))) works for me Commented Oct 31, 2017 at 3:08
  • @JacobIRR which version of python you are using? Commented Oct 31, 2017 at 3:11
  • >>> sys.version '3.6.1...' Commented Oct 31, 2017 at 3:12
  • Same error I got in online compiler rextester.com/l/python3_online_compiler Commented Oct 31, 2017 at 3:15
  • 1
    I'm sure you'll find plenty of ways to fix this by googling "python write bytes to file" Commented Oct 31, 2017 at 3:17

1 Answer 1

45

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.