How do you fix UnicodeDecodeError when reading a CSV file with Pandas? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you fix UnicodeDecodeError when reading a CSV file with Pandas?

message-square
0

Pass the file’s actual character encoding to pd.read_csv("file.csv", encoding="...")—most commonly encoding="cp1252" (Windows-1252) or encoding="latin-1" (ISO-8859-1) when reading CSVs exported from Microsoft Excel on Windows, or encoding="utf-8-sig" when a UTF-8 file starts with a Byte Order Mark (BOM) that pollutes the first column name with \ufeff.

Basic Example

import pandas as pd

# 1. Recommended for Excel / Windows CSV exports (`0x92`, `0x96`, `0x80`, `0xe9` byte errors):
df_win = pd.read_csv("sales_export.csv", encoding="cp1252")

# 2. Recommended for UTF-8 CSVs with BOM (prevents `'\ufeffid'` in `df.columns[0]`):
df_utf8_bom = pd.read_csv("utf8_bom_export.csv", encoding="utf-8-sig")

# 3. Last-resort fallback when a file contains corrupted mixed bytes (`encoding_errors=`):
df_lossy = pd.read_csv(
    "corrupted_logs.csv",
    encoding="utf-8",
    encoding_errors="replace",  # Replaces invalid byte sequences with `\ufffd` (``)
)

Key Details & Edge Cases

  • Diagnosing the exact encoding from the failing byte in the traceback:
    • UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 / 0x93 / 0x94 / 0x96 / 0x80 $\rightarrow$ Almost always Windows-1252 (encoding="cp1252"), produced by Excel “CSV (Comma delimited) (*.csv)” exports containing smart quotes, em-dashes, or €.
    • UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff / 0xfe in position 0 $\rightarrow$ The file is UTF-16 (Excel “Unicode Text” export, often tab-separated). Read with pd.read_csv("file.csv", encoding="utf-16", sep="\t").
  • Why encoding="latin-1" never raises UnicodeDecodeError (and why cp1252 is usually better):
    • latin-1 maps every single byte value 0x00–0xFF 1-to-1 to Unicode code points U+0000–U+00FF, so it will never crash—however, bytes 0x80–0x9F map to invisible C1 control characters instead of Windows characters (€, “, ”, —). Try encoding="cp1252" first for Windows files, and reserve latin-1 for unknown legacy binary-text dumps.
  • Fixing silent \ufeff BOM corruption on the first column header:
    • Reading a UTF-8-BOM file with encoding="utf-8" succeeds without an error, but silently names the first column "\ufeffuser_id", causing KeyError: 'user_id'. Using encoding="utf-8-sig" strips the leading BOM automatically while behaving identically to "utf-8" on standard UTF-8 files.
  • Auto-detecting unknown encodings with charset-normalizer (or chardet):
    • When ingesting arbitrary user uploads whose encoding is unknown ahead of time, inspect the raw leading bytes before calling pd.read_csv():
      from charset_normalizer import from_path
      
      best_match = from_path("unknown.csv").best()
      detected_encoding = best_match.encoding if best_match else "utf-8"
      df = pd.read_csv("unknown.csv", encoding=detected_encoding)
      
  • Pandas encoding_errors parameter (Pandas 1.3+):
    • Instead of pre-opening the file manually with open(..., errors="replace"), pass encoding_errors="replace" (substitutes ``) or encoding_errors="ignore" (drops invalid bytes) directly into pd.read_csv() when recovering partially corrupted logs.

Comparison of pd.read_csv() Encoding Options

Encoding Argument Handles Excel Windows Exports (0x80–0x9F)? Strips UTF-8 BOM (\ufeff)? Can Still Raise UnicodeDecodeError? Best Used When
encoding="utf-8-sig" (Recommended default for UTF-8) No (UTF-8 only) Yes Yes (on non-UTF-8 bytes) Modern UTF-8 CSVs, including Excel “CSV UTF-8” exports that prepend a BOM.
encoding="cp1252" (Recommended for Windows CSVs) Yes (maps €, smart quotes, dashes cleanly) No Yes (rarely, on undefined bytes 0x81, 0x8D, 0x8F, 0x90, 0x9D) Legacy CSV exports from Microsoft Excel or Windows applications in Western locales.
encoding="latin-1" (ISO-8859-1) Partial (decodes 0x80–0x9F as control chars) No No (every byte 0x00–0xFF is valid) Legacy European datasets or inspecting files with unknown single-byte encodings without crashing.
encoding="utf-16" (often with sep="\t") Yes (full Unicode BMP/supplementary) Yes (reads FF FE / FE FF BOM) Yes (on non-UTF-16 files) Files failing at byte position 0 with 0xff or 0xfe (Excel “Unicode Text” exports).
encoding="utf-8", encoding_errors="replace" No (substitutes `` for invalid bytes) No (use "utf-8-sig" to strip BOM) No Salvaging mostly UTF-8 log files or scraped CSVs with scattered corrupted bytes.