Typeerror: write() argument must be STR, not bytes and the method of writing binary file in Python 3

Python 2 writes binary file randomly:

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

However, using Python 3 will report an error:

TypeError:must be str, not bytes

The reason is: Python 3 adds a new parameter named encoding to the open function, and the default value of this new parameter is “UTF-8”. In this way, when the read and write operations are carried out on the file handle, the system requires the developer to pass in the instance containing Unicode characters instead of the byte instance containing binary data.

resolvent:

Use binary write mode (“WB”) to open the file to be operated, instead of using character write mode (“W”) as before.

The method of adapting both Python 3 and python 2 is as follows

with open('python3/rndom.bin','wb') as f:
    f.write(os.urandom(10))

There is a similar problem when the file reads data. The solution to this problem is similar: open the file in ‘RB’ mode (binary mode) instead of ‘R’ mode.

Reproduced in: https://www.cnblogs.com/circleyuan/p/10350202.html

Read More: