W3docs

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

The "UnicodeDecodeError: 'ascii' codec can't decode byte" error occurs when trying to decode non-ASCII bytes using the ASCII codec.

The "UnicodeDecodeError: 'ascii' codec can't decode byte" error occurs when trying to decode non-ASCII bytes using the ASCII codec. To fix this, you can specify the correct codec when opening the file or when calling the decode method. Here is an example of how to fix the error by specifying the UTF-8 codec when opening a file:

fix UnicodeDecodeError in Python

with open('file.txt', 'r', encoding='utf-8') as f:
    content = f.read()

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the decode method on the bytes to specify the codec:

fix UnicodeDecodeError specifying the codec

content = b'...'.decode('utf-8')

It's important to note that the correct codec to use depends on the file you are trying to read. UTF-8 is a commonly used codec for text files, but other codecs such as UTF-16 and ISO-8859-1 may also be used.