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 as0x92(smart apostrophe’),0xe9(é), or0xffviolate UTF-8’s continuation rules and trigger an immediateUnicodeDecodeError. - Identifying the exact encoding from the failing byte:
0x91,0x92,0x93,0x94,0x96,0x97: Classic Microsoft smart quotes and dashes fromcp1252(windows-1252)—extremely common in Excel CSV exports and Windows text files.0xffor0xfeatposition 0: A Byte Order Mark (BOM) indicatingutf-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 incp1252orlatin-1(iso-8859-1).- Accidental binary file: If the file is actually a
.xlsx,.zip,.pdf,.pkl, or.pngopened in text mode ("r"), switch to binary mode ("rb") or use the proper parser (pd.read_excel()instead ofpd.read_csv()).
- Auto-detecting unknown encodings (
charset-normalizerorchardet): If you receive files with unpredictable encodings, inspect the raw bytes first with `charset-normalizer
You must log in or register to comment.
