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 withpd.read_csv("file.csv", encoding="utf-16", sep="\t").
- Why
encoding="latin-1"never raisesUnicodeDecodeError(and whycp1252is usually better):latin-1maps every single byte value0x00–0xFF1-to-1 to Unicode code pointsU+0000–U+00FF, so it will never crash—however, bytes0x80–0x9Fmap to invisible C1 control characters instead of Windows characters (€,“,”,—). Tryencoding="cp1252"first for Windows files, and reservelatin-1for unknown legacy binary-text dumps.
- Fixing silent
\ufeffBOM 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", causingKeyError: 'user_id'. Usingencoding="utf-8-sig"strips the leading BOM automatically while behaving identically to"utf-8"on standard UTF-8 files.
- Reading a UTF-8-BOM file with
- Auto-detecting unknown encodings with
charset-normalizer(orchardet):- 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)
- When ingesting arbitrary user uploads whose encoding is unknown ahead of time, inspect the raw leading bytes before calling
- Pandas
encoding_errorsparameter (Pandas 1.3+):- Instead of pre-opening the file manually with
open(..., errors="replace"), passencoding_errors="replace"(substitutes ``) orencoding_errors="ignore"(drops invalid bytes) directly intopd.read_csv()when recovering partially corrupted logs.
- Instead of pre-opening the file manually with
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. |
You must log in or register to comment.
