LookupError: unknown encoding in Python [Solved]

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')

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link