How do you fix "UnicodeDecodeError: 'utf8' codec can't decode byte" in Python? | A1Lab@MZeeshanM to PythonEnglish • 5 days ago

How do you fix "UnicodeDecodeError: 'utf8' codec can't decode byte" in Python?

message-square
0

Specify the file’s actual character encoding (such as encoding="cp1252" or encoding="latin-1") instead of the default "utf-8" when calling open(), Path.read_text(), or pd.read_csv(), or pass errors="replace" / errors="ignore" if the file contains isolated corrupted bytes that you can safely discard or substitute.

Basic Example

# WRONG: Reading a Windows-1252 / Latin-1 encoded file with default UTF-8 raises UnicodeDecodeError
# with open("legacy_export.csv", "r", encoding="utf-8") as f:
#     content = f.read()
# -> UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 14: invalid start byte

# 1. FIX A (Recommended): Pass the file's actual encoding (e.g., Windows-1252 or UTF-16)
with open("legacy_export.csv", "r", encoding="cp1252") as file:
    content = file.read()

# 2. FIX B (Pandas): Specify encoding in pd.read_csv()
import pandas as pd

df = pd.read_csv("legacy_export.csv", encoding="cp1252")

# 3. FIX C (Corrupted mixed bytes): Replace invalid byte sequences with '' instead of crashing
with open("noisy_log.txt", "r", encoding="utf-8", errors="replace") as file:
    safe_content = file.read()

Key Details & Diagnostic Clues

  • Why UnicodeDecodeError: 'utf-8' codec can't decode byte... happens: UTF-8 enforces strict multi-byte bit patterns for bytes $\ge \text{0x80}$ (128). When Python reads a file encoded in a legacy single-byte encoding (like Windows-1252 or ISO-8859-1) or UTF-16, raw bytes such as 0x92 (smart apostrophe ’), 0xe9 (é), or 0xff violate UTF-8’s continuation rules and trigger an immediate UnicodeDecodeError.
  • Identifying the exact encoding from the failing byte:
    • 0x91, 0x92, 0x93, 0x94, 0x96, 0x97: Classic Microsoft smart quotes and dashes from cp1252 (windows-1252)—extremely common in Excel CSV exports and Windows text files.
    • 0xff or 0xfe at position 0: A Byte Order Mark (BOM) indicating utf-16 (utf-16-le / utf-16-be), commonly produced by Windows PowerShell (Out-File / >) or SQL Server exports.
    • 0xe9, 0xe0, 0xfc, 0xf1: Accented Western European characters (é, à, ü, ñ) encoded in cp1252 or latin-1 (iso-8859-1).
    • Accidental binary file: If the file is actually a .xlsx, .zip, .pdf, .pkl, or .png opened in text mode ("r"), switch to binary mode ("rb") or use the proper parser (pd.read_excel() instead of pd.read_csv()).
  • Auto-detecting unknown encodings (charset-normalizer or chardet): If you receive files with unpredictable encodings, inspect the raw bytes first with `charset-normalizer