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

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

message-square
0

Specify encoding="cp1252" (Windows-1252) when opening the file (open("file.txt", encoding="cp1252") or pd.read_csv("file.csv", encoding="cp1252")), because byte 0x9c is the Windows-1252 encoding for the lowercase oe ligature œ (and is undefined/invalid in UTF-8 and ISO-8859-1/Latin-1, where 0x80–0x9F are non-printable control characters).

Basic Example

from pathlib import Path
import pandas as pd

# 1. Recommended for standard file reading (Windows-1252 / ANSI text files):
with open("report.txt", mode="r", encoding="cp1252") as f:
    text = f.read()

# Or with pathlib.Path:
content = Path("report.txt").read_text(encoding="cp1252")

# 2. Recommended for Pandas CSV / delimited text ingestion:
df = pd.read_csv("export.csv", encoding="cp1252")

# 3. Fallback for messy/corrupted logs with mixed encodings (replaces bad bytes with ):
with open("mixed_log.txt", mode="r", encoding="utf-8", errors="replace") as f:
    clean_text = f.read()

Key Details & Edge Cases

  • Why byte 0x9c specifically proves the file is Windows-1252 (cp1252) rather than latin-1:
    • In UTF-8, single bytes in the 0x80–0xBF range are continuation bytes that cannot start a multi-byte character, immediately triggering UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9c in position ...: invalid start byte.
    • In Windows-1252 (cp1252, the legacy default encoding on Western Windows machines and older Excel CSV exports), bytes 0x80–0x9F map to printable characters such as smart quotes (0x93/0x94), em-dashes (0x97), the euro sign (0x80), and œ (0x9c)—whereas ISO-8859-1 (latin-1) maps 0x9c to an invisible C1 control code (STRING TERMINATOR) rather than œ.
  • Re-save legacy cp1252 files to clean utf-8 once decoded:
    • If your pipeline expects UTF-8 downstream, decode with encoding="cp1252" and write back out with encoding="utf-8" so subsequent tools never fail again:
      p = Path("legacy.csv")
      p.write_text(p.read_text(encoding="cp1252"), encoding="utf-8")
      
  • When you don’t know the file’s encoding ahead of time (charset-normalizer / chardet):
    • If files come from arbitrary international Windows locales (e.g., cp1251 Cyrillic, cp1256 Arabic, shift_jis Japanese), inspect the raw bytes with charset-normalizer (pip install charset-normalizer, used internally by requests):
      from charset_normalizer import from_path
      best_guess = from_path("unknown.txt").best()
      print(best_guess.encoding, str(best_guess)[:100])
      
  • Never open binary files (.xlsx, .zip, .pdf, .pkl, .sqlite) in text mode ("r"):
    • Opening a binary file with open("data.xlsx", "r") forces Python to decode raw binary bytes as UTF-8, frequently failing on byte 0x9c or 0x90. Use binary mode ("rb") or a dedicated parser (pd.read_excel("data.xlsx")).

Comparison of Decoding Strategies for Byte 0x9c (UnicodeDecodeError)

Strategy Syntax Preserves œ & Smart Punctuation? Risk of Silent Data Corruption? Best Used When
encoding="cp1252" (Recommended) open(path, encoding="cp1252") Yes (0x9c $\rightarrow$ œ) Low (fails on undefined bytes 0x81, 0x8D, 0x8F, 0x90, 0x9D) Reading files exported from Windows apps, Excel, or legacy Western European databases.
encoding="utf-8", errors="replace" open(path, encoding="utf-8", errors="replace") No (replaces 0x9c with \ufffd ``) Medium (loses original character) Scraping or parsing mostly-UTF-8 logs containing a few stray corrupted bytes.
encoding="latin-1" (iso-8859-1) open(path, encoding="latin-1") No (0x9c becomes control char \x9c) High (never raises an error, even on binary garbage) Reading raw byte-to-codepoint streams where every 0x00–0xFF byte must round-trip 1:1.
charset_normalizer.from_path() str(from_path(path).best()) Yes (auto-detects cp1252, cp1251, etc.) Low Processing user-uploaded files with unknown regional encodings.