How to Fix Python Encoding Error When Reading Files
In this tutorial, you'll learn about How to Fix Python Encoding Error When Reading Files. We cover key concepts, practical examples, and best practices.
Python raises UnicodeDecodeError when reading a file with the wrong encoding, or produces garbled text when the encoding is not specified correctly.
The Wrong Way
with open('data.txt', 'r') as f:
content = f.read()
print(content)
This produces:
Traceback (most recent call last):
File "script.py", line 2, in <module>
content = f.read()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 10: invalid continuation byte
The Right Way
Specify the correct encoding when opening the file:
with open('data.txt', 'r', encoding='latin-1') as f:
content = f.read()
print(content)
Step-by-Step Fix
1. Detect the file encoding
python3 -c "
with open('data.txt', 'rb') as f:
print(f.read()[:100])
"
Or use chardet:
pip install chardet
python3 -c "
import chardet
with open('data.txt', 'rb') as f:
result = chardet.detect(f.read(10000))
print(result)
"
2. Try common encodings
encodings = ['utf-8', 'latin-1', 'cp1252', 'iso-8859-1', 'utf-16']
for enc in encodings:
try:
with open('data.txt', 'r', encoding=enc) as f:
content = f.read()
print(f"Success with {enc}")
break
except UnicodeDecodeError:
continue
3. Use errors='replace' for problematic files
with open('data.txt', 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
# Bad bytes are replaced with the replacement character
4. Read in binary mode and decode manually
with open('data.txt', 'rb') as f:
raw = f.read()
try:
text = raw.decode('utf-8')
except UnicodeDecodeError:
text = raw.decode('latin-1')
5. Use pathlib with encoding
from pathlib import Path
content = Path('data.txt').read_text(encoding='utf-8', errors='replace')
Prevention Tips
- Always specify
encoding='utf-8'when opening files. - Save all your files as UTF-8 to avoid encoding issues.
- Use
errors='replace'when reading untrusted file sources. - Use
chardetto detect encoding of unknown files. - Use
pathlib.Path.read_text()instead of bareopen().
Common Mistakes with encoding error
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty 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