Why LookupError: unknown encoding in Python Error occurs?
The “LookupError: unknown encoding” Python occurs when you specify an encoding that is not supported by the python intereprter.
Let’s know why the error comes.
with open('abc.txt', 'w', encoding='abc') as my_file:
my_file.write('first' + '\n')
my_file.write('second' + '\n')
my_file.write('third' + '\n')
You will get the error when you will run the above codes as abc encoding is not supported.
Solution of LookupError: unknown encoding Error
1. Use the supported encoding
Use the utf-8 encoding or use any other standard encodings that suit your use case, e.g. latin-1 or ascii. It can solve the error.
Taking the same above code, if you will use the utf-8 encoding then you will not get the error.
with open('abc.txt', 'w', encoding='utf-8') as my_file:
my_file.write('first' + '\n')
my_file.write('second' + '\n')
my_file.write('third' + '\n')
2. Set the PYTHONIOENCODING environment variable
The other solution for this error is to set the PYTHONIOENCODING environment variable to the current encoding.
On Windows run the below command.
setx PYTHONIOENCODING=utf-8
setx PYTHONLEGACYWINDOWSSTDIO=utf-8
On Linux or MacOs
export PYTHONIOENCODING=utf-8
Othe causes
1. Calling the encode() method wrongly
You will get the error when you will use the encode() function on the unknown encoding. Below is an example of it.
my_bytes = 'codethebest.com'.encode('utf200')
The solution to this problem is the same. Just pass the correct encoding like the above.
my_bytes = 'codethebest.com'.encode('utf-8')
Leave a Reply