LookupError: unknown encoding in Python

avatar

Borislav Hadzhiev

Last updated: Apr 30, 2022

banner

Photo from Unsplash

LookupError: unknown encoding in Python #

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.

lookuperror unknown encoding

Here is an example of how the error occurs.

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

Chances are you meant to use the utf-8 encoding, which is capable of encoding over a million valid character code points in Unicode.

main.py
# ✅ 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 and utf-32.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.