Skip to content

How to Fix UnicodeDecodeError in Python

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix UnicodeDecodeError in Python. We cover key concepts, practical examples, and best practices.

Python raises UnicodeDecodeError when attempting to decode a byte string using a codec that cannot handle the byte values present in the data.

The Wrong Way

data = b'\xe0\xa4\xa4\xe0\xa5\x87\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\x9f'
text = data.decode('ascii')
print(text)

This produces:

Traceback (most recent call last):
  File "script.py", line 2, in <module>
    text = data.decode('ascii')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)

The Right Way

Use the correct encoding for the data:

data = b'\xe0\xa4\xa4\xe0\xa5\x87\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\x9f'
text = data.decode('utf-8')
print(text)

Output:

test

Step-by-Step Fix

1. Use the correct encoding

Most text files are UTF-8. Specify the encoding explicitly:

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

2. Use errors='replace' to handle bad bytes

data = b'Hello\x80World'
text = data.decode('utf-8', errors='replace')
print(text)

Output:

Hello�World

3. Detect encoding automatically

import chardet

data = b'\xff\xfeH\x00e\x00l\x00l\x00o\x00'
result = chardet.detect(data)
encoding = result['encoding']
print(f"Detected encoding: {encoding}")
text = data.decode(encoding)
print(text)

4. Use latin-1 as a fallback (never fails)

data = b'\xe0\xa4\xa4'
try:
    text = data.decode('utf-8')
except UnicodeDecodeError:
    text = data.decode('latin-1')
    print("Falling back to latin-1")

Prevention Tips

  • Always open files with an explicit encoding='utf-8' parameter.
  • Use errors='replace' or errors='ignore' when decoding untrusted data.
  • Use the chardet library to detect encoding of unknown data.
  • Prefer pathlib.Path.read_text(encoding='utf-8') over bare open().
  • Store all text data as UTF-8 to avoid encoding issues.

Common Mistakes with unicodedecode

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' causing stack overflow on large lists

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the default encoding in Python 3?

Python 3 uses UTF-8 as the default source encoding. However, open() without explicit encoding uses the system locale, which may be ASCII or another encoding on some platforms. Always specify encoding explicitly.

What does errors='replace' do?

It replaces undecodable bytes with the Unicode replacement character U+FFFD (a question mark in a diamond). This prevents the decode operation from raising an error while preserving most of the text.

How do I find the encoding of an unknown file?

Use chardet.detect() or python3 -c "print(open('file', 'rb').read()[:100])" to inspect the raw bytes. Common encodings are UTF-8, UTF-16 (with BOM), latin-1, and cp1252.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro