ValueError: binary mode doesn't take an encoding argument

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Erik Mclean

ValueError: binary mode doesn't take an encoding argument #

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.

valueerror binary mode doesnt take an encoding argument

Here is an example of how the error occurs.

main.py
# ⛔️ 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.

main.py
with open('example.txt', 'rb') as f: result = f.readlines() print(result)
The 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.

main.py
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).

Note that if you don't explicitly set the 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.

If you append a 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.