How to Fix UnicodeDecodeError in Python
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'orerrors='ignore'when decoding untrusted data. - Use the
chardetlibrary to detect encoding of unknown data. - Prefer
pathlib.Path.read_text(encoding='utf-8')over bareopen(). - Store all text data as UTF-8 to avoid encoding issues.
Common Mistakes with unicodedecode
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'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
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro