Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Velvet Morris
The Python "TypeError: write() argument must be str, not bytes" occurs when we
try to write bytes to a file without opening the file in wb
mode. To solve the
error, open the file in wb
mode to write bytes or decode the bytes object into
a string.
Here is an example of how the error occurs.
with open('example.txt', 'w') as my_file: # ⛔️ TypeError: write() argument must be str, not bytes my_file.write(b'hello world')
We opened the file in w
mode and tried writing bytes which caused the error.
If you need to write bytes to a file, open in it wb
(binary) mode rather than
w
(text) mode.
# ✅ open file in wb mode with open('example.txt', 'wb') as my_file: my_file.write(b'hello world')
We opened the file in wb
(binary) mode to write bytes to it.
Note that you shouldn't specify the encoding
keyword argument when you open a
file in binary mode.
Alternatively, you can decode the bytes object into a string.
with open('example.txt', 'w', encoding='utf-8') as my_file: my_file.write(b'hello world'.decode('utf-8'))
We opened the JSON file in w
(text) mode.
When a file is opened in text mode, we read and write strings from and to the file.
Those strings are encoded using a specific encoding (utf-8
in the example).
encoding
keyword argument, the default is platform-dependent.If you want to both read from and write to the file, use the r+
mode when
opening it.
b
to the mode (like in the first code snippet), the file is opened in binary mode.Note that you cannot specify encoding
when opening a file in binary mode.
When a file is opened in binary mode, data is read and written as bytes
objects.
The bytes.decode
method returns a string decoded from the given bytes. The default encoding is
utf-8
.
with open('example.txt', 'w', encoding='utf-8') as my_file: my_file.write(b'hello world'.decode('utf-8'))
You can decode your bytes object to a string if you want to write strings to the file.
Conversely, the
str.encode method
returns an encoded version of the string as a bytes object. The default encoding
is utf-8
.
with open('example.txt', 'wb') as my_file: my_file.write('hello world'.encode('utf-8'))
The example shows how to encode a string to a bytes object and write the bytes to a file.