How to Resolve "LookupError: unknown encoding" in Python
The LookupError: unknown encoding
error in Python occurs when you try to use an encoding that Python doesn't recognize. This typically happens when opening files, encoding/decoding strings, or configuring standard input/output.
This guide explains the causes of this error and provides solutions, including using valid encodings, setting environment variables, and reconfiguring sys.stdin
and sys.stdout
.
Understanding the Error: Invalid Encoding
The LookupError: unknown encoding
error means you've specified an encoding name that Python's codec registry doesn't know. This most commonly happens in these situations:
- Opening files:
open('filename.txt', 'r', encoding='invalid-encoding')
- Encoding/Decoding strings:
'my string'.encode('invalid-encoding')
orb'my bytes'.decode('invalid-encoding')
- Changing Standard Input/Output Encoding.
Example of the error:
# ⛔️ LookupError: unknown encoding: example
with open('example.txt', 'w', encoding='example') as my_file: # 'example' is invalid
my_file.write('first line' + '\n')