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

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.

Leave a Comment