What causes "UnicodeDecodeError: invalid continuation byte" and how do you fix it? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

What causes ""UnicodeDecodeError: invalid continuation byte"" and how do you fix it?

message-square
0

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xXX in position Y: invalid continuation byte occurs when Python attempts to decode non-UTF-8 binary data (most commonly legacy single-byte encodings like cp1252, latin-1 / iso-8859-1, or raw compressed/binary bytes) using the utf-8 codec—fix it by specifying the file’s actual character encoding (such as encoding="cp1252" or encoding="latin-1"), opening binary files in "rb" mode, or passing errors="replace" when recovering partially corrupted text.

Basic Example

# Simulate bytes encoded in Windows-1252 / Latin-1 (0x93 = “ and 0xe9 = é)
raw_bytes = b"Caf\xe9 \x93Special\x94"

# WRONG: Decoding non-UTF-8 bytes with UTF-8 fails on 0xe9 followed by space (0x20, not 0x80..0xBF)
# raw_bytes.decode("utf-8")
# -> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte

# 1. FIX A (Recommended): Decode using the file's true encoding (cp1252 or latin-1)
print(raw_bytes.decode("cp1252"))  # Output: Café “Special”

# 2. FIX B: Specify the matching encoding when reading files or CSVs
with open("legacy_export.txt", "r", encoding="cp1252") as f:
    text = f.read()

# 3. FIX C: Use errors="replace" if the file is mostly UTF-8 with isolated corrupted bytes
print(raw_bytes.decode("utf-8", errors="replace"))  # Output: Caf Special

Key Details & Edge Cases

  • Why UTF-8 specifically reports "invalid continuation byte":
    • In UTF-8, any leading byte between 0xC2 and 0xF4 signals a multi-byte sequence where the next 1 to 3 bytes must be continuation bytes in the bit pattern 10xxxxxx (0x80–0xBF).
    • In single-byte encodings like latin-1 (ISO-8859-1) or cp1252 (Windows Western European), accented characters like é (0xE9), ü (0xFC), or ñ (0xF1) are stored as a single byte followed immediately by standard ASCII letters or spaces (0x00–0x7F). When UTF-8 sees 0xE9 (11101001, a 3-byte starter) followed by ASCII 0x20 (00100000), it aborts with invalid continuation byte.
  • cp1252 vs. latin-1 (iso-8859-1)—which should you pick?
    • cp1252 (Windows-1252): A superset of iso-8859-1 for printable characters that maps bytes 0x80–0x9F to smart quotes (“, ”), em-dashes (—), trademarks (™), and the Euro sign (€). Use encoding="cp1252" for files exported from Windows Excel, Notepad, or legacy SQL Server/Access databases.
    • latin-1 (iso-8859-1): Maps every single byte 0x00–0xFF 1-to-1 to Unicode code points U+0000–U+00FF. It never raises UnicodeDecodeError, making it useful for raw byte-preserving round-trips, though bytes 0x80–0x9F decode into invisible C1 control characters instead of smart quotes.
  • Accidental binary file reads ("rb" vs. "r"): Trying to read .zip, .gz, .xlsx, .parquet, .pkl, or image files with open(path, "r") (text mode) triggers invalid continuation byte immediately on magic header bytes (e.g., Gzip’s 0x1f 0x8b). Open compressed or binary formats in "rb" mode (or use gzip.open(..., "rt", encoding="utf-8")).
  • Auto-detecting unknown encodings (charset-normalizer / chardet): When ingesting third-party files with unknown encodings, inspect a byte sample before decoding:
    from charset_normalizer import from_path
    
    best_match = from_path("unknown_file.csv").best()
    print(best_match.encoding)  # e.g., 'cp1252' or 'utf_8'
    text = str(best_match)
    

Diagnostic & Resolution Reference

Suspected Source of Bytes Likely Cause Clean Fix
Windows Excel / CSV / ERP export File encoded in Windows-1252 (cp1252) instead of UTF-8 open(path, encoding="cp1252") or pd.read_csv(path, encoding="cp1252")
Older European / HTTP / SQL text File encoded in ISO-8859-1 (latin-1) open(path, encoding="latin-1")
Compressed or binary file (.gz, .zip, .xlsx) Binary file opened in text mode ("r") instead of binary mode Open with "rb" or use format-specific readers (gzip.open, pd.read_excel)
Unknown third-party file encoding Mixed or undocumented legacy encoding Detect via charset_normalizer.from_path(path).best()
Mostly UTF-8 log with stray bad bytes Truncated multi-byte sequence or corrupted byte in stream open(path, encoding="utf-8", errors="replace") (or errors="backslashreplace")