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:
- Typeerror: write() argument must be STR, not bytes and the method of writing binary file in Python 3
- typeerror:the josn object must be str,bytes or byteearray,not ‘dict‘
- Type error: the JSON object must be STR, bytes or byte array, not ‘textiowrapper’
- python reads csv file is an error _csv.Error: iterator should return strings, not bytes (did you open the file in text)
- Python about typeerror: required argument ‘mat’ (POS 2) not found error resolution
- Error writing to file in Python installation
- “Typeerror: List indexes must be integers or slices, not STR” about error reporting solutions
- TypeError(‘Keyword argument not understood:‘, ‘***‘) in keras.models load_model
- python-TypeError: list indices must be integers, not tuple Solution
- Python TypeError: ‘newline’ is an invalid keyword argument for this function
- Python error prompt: typeerror: ‘builtin’_ function_ or_ method‘ object is not subscriptable
- python SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: trunca
- Arduino reports an error when writing a custom library file to solve the problem of not name of type, not declared in this scope
- Module build failed: TypeError [ERR_INVALID_ARG_TYPE]: The “path“ argument must be of type string.
- Error reported in Python reading file oserror: [errno 22] invalid argument: ‘u202ac: \ \ users \ \ yyqhk \ \ desktop \ \ 1. CSV’
- TypeError: Required argument ‘mat‘ (pos 2) not found
- Python read / write file error valueerror: I/O operation on closed file
- Python TypeError: return arrays must be of ArrayType
- Python – writing visual interface (Python + pycharm + pyqt)
- PySpark ERROR Shell: Failed to locate the winutils binary in the hadoop binary path