LookupError: unknown encoding in Python [RESOLVED]

LookupError: unknown encoding in Python [RESOLVED]

When we specify an encoding that is not supported, the Python "LookupError: unknown encoding" error occurs. To resolve the error, use the utf-8 encoding or any of the other standard encodings that are appropriate for your use case, such as latin-1 or ascii.

Error - LookupError: unknown encoding

Here's an illustration 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 used an encoding that was not on the list of standard encodings, which resulted in the error. Most likely, you meant to use the utf-8 encoding, which can encode over a million valid Unicode character code points.

Solution

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

Encoding Types in Python

Python's inbuilt codecs include several different formats, which are either C functions or dictionary mapping tables. Here's a rundown of the most popular codecs, their alternate names, and the languages they're most commonly used with. These lists of aliases and languages are not meant to be comprehensive. Note that 'utf-8' is a valid alias for the 'utf 8' codec, just like 'utf-16' is a valid alias for the 'utf-16' codec, and so on.

You can find the list of standard encodings supported by Python in this table.