Skip to content

How to Fix Python Encoding Error When Reading Files

DodaTech Updated 2026-06-24 2 min read

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 chardet to detect encoding of unknown files.
  • Use pathlib.Path.read_text() instead of bare open().

Common Mistakes with encoding error

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

### What is the default encoding for open() in Python?

The default encoding depends on your system locale. On Linux it is usually UTF-8, but on Windows it may be the system's ANSI code page (like cp1252). Always specify encoding explicitly for portability.

How do I find the encoding of a file?

Use file data.txt in the terminal, or chardet.detect() in Python. The python3 -m json.tool approach works for JSON files. Most modern files are UTF-8.

What does errors='replace' do?

It substitutes undecodable byte sequences with the Unicode replacement character U+FFFD (displayed as a question mark in a diamond). This allows the file to be read without crashing, though some data is lost.

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

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro