Last updated: Apr 8, 2024
Reading time·2 min
The Python "LookupError: unknown encoding" occurs when we specify an encoding that is not supported.
To solve the error, use the utf-8
encoding or pick any of the other standard
encodings that suit your use case, e.g. latin-1
or ascii
.
Here is an example of how the error occurs.
# ⛔️ LookupError: unknown encoding: example with open('example.txt', 'w', encoding='example') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')
We specified an encoding that is not in the list of standard encodings which caused the error.
utf-8
encoding insteadChances are you meant to use the utf-8
encoding which is capable of encoding
over a million valid character code points in Unicode.
# ✅ Specify 'utf-8' encoding with open('example.txt', 'w', encoding='utf-8') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')
You can view all of the standard encodings in this table of the official docs.
Some of the common encodings are ascii
, latin-1
, utf-16
and utf-32
.
The error also occurs when you call the encode()
method with an unknown
encoding.
# ⛔️ LookupError: unknown encoding: utf100 my_bytes = 'bobbyhadz.com'.encode('utf100')
The solution is the same, make sure to pass the correct encoding in the call to
str.encode()
, e.g. utf-8
.
my_bytes = 'bobbyhadz.com'.encode('utf-8') print(my_bytes) # 👉️ b'bobbyhadz.com'
The str.encode() method returns an
encoded version of the string as a bytes object. The default encoding is
utf-8
.
You can view all of the standard encodings in this table of the official docs.
PYTHONIOENCODING
environment variableIf the error persists, try to set the PYTHONIOENCODING
environment variable.
# On Linux and macOS export PYTHONIOENCODING=utf-8 # On Windows setx PYTHONIOENCODING=utf-8 setx PYTHONLEGACYWINDOWSSTDIO=utf-8
If the
PYTHONIOENCODING
environment variable is set before running the interpreter, it overrides the
encoding used for stdin
and stdout
.
If you are on Windows, you also have to set the PYTHONLEGACYWINDOWSSTDIO environment variable.
You can also set the encoding globally by adding the following lines to the top of your file.
import sys sys.stdin.reconfigure(encoding='utf-8') sys.stdout.reconfigure(encoding='utf-8')
The 3 lines of code override the encoding used for stdin
and stdout
.