Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Erik Mclean
The Python "ValueError: binary mode doesn't take an encoding argument" occurs
when we open a file in binary mode (rb
or wb
) and set the encoding
keyword
argument. To solve the error, either open the file in text mode (r
or w
) or
remove the encoding
keyword argument.
Here is an example of how the error occurs.
# ⛔️ ValueError: binary mode doesn't take an encoding argument with open('example.txt', 'rb', encoding='utf-8') as f: result = f.readlines() print(result)
We opened the file in rb
(binary) mode rather than r
(text) mode and set the
encoding
keyword argument which caused the error.
The same is the case if you open the file in wb
(write binary) mode rather
than w
(write text) mode.
If you are reading from or writing to a binary file, keep the mode and remove
the encoding
keyword argument.
with open('example.txt', 'rb') as f: result = f.readlines() print(result)
encoding
keyword argument is only relevant when reading from and writing to text files.If you are reading from or writing to text files, remove the b
character from
the mode and set the encoding
keyword argument.
with open('example.txt', 'r', encoding='utf-8') as f: result = f.readlines() print(result)
You can use the w
mode if writing to a text file.
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.