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.
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.
- Typeerror: write() argument must be STR, not bytes and the method of writing binary file in Python 3
- Translate() and maketrans() methods of string in Python
- Modification scheme of binary files in dot matrix font library
- python SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: trunca
- Run Python file for the first time with eclipse / pydev: “UTF-8 ‘codec can’t decode byte 0xc4 in position
- LoadRunner error — memory violation: exception access_ Solution
- MySQL modify character set
- Raspberry pie 4B uses adafruit_ Pca9685 report error ioerror: [errno 121] remote I / O error solution
- Write about the problems and solutions when configuring OpenGL in vs2015
- Java long type error: error: integer number too large
- Parsing the difference between “R” and “RB” patterns of text files (Python)
- Compiler error message: cs1056: unexpected character handling
- Successfully resolved Unicode decodeerror: ‘UTF-8’ codec can’t decode byte 0xd3 in position 238: invalid continuation B
- Vs2013 error msb8031 solution today ran a MFC program, found that the error: error msb8031: building an MFC project for a non-U
- Unicode decodeerror: ‘UTF-8’ codec can’t decode byte 0xd3 in position 238: invalid continuation B
- The use of Chinese characters in Qt and the solution to the “error C2001: newline in constant” problem
- Spoop export hive to MySQL
- ASP.NET How to deal with “unexpected character” when writing code
- Error cs1010 cs8025 cs1012 cs1525 common document error resolution
- Error C2664 in C + + compilation: cannot convert parameter 2 from “const char ” to “lpctstr” solution.