How do you fix "UnicodeDecodeError: 'charmap' codec can't decode byte" in Python on Windows? | A1Lab@MZeeshanM to PythonEnglish • 5 days ago

"How do you fix ""UnicodeDecodeError: 'charmap' codec can't decode byte"" in Python on Windows?"

message-square
0

Specify encoding="utf-8" explicitly whenever calling open(), Path.read_text(), or pd.read_csv() on Windows—because Windows Python defaults to the legacy system code page (cp1252, reported as 'charmap') instead of UTF-8 when encoding is omitted, causing multi-byte UTF-8 characters (such as emojis, accented text, em-dashes, or non-Latin scripts) to fail on unassigned byte values like 0x81, 0x8d, 0x8f, 0x90, or 0x9d.

Basic Example

# WRONG on Windows: open() omits 'encoding', defaulting to Windows-1252 ('charmap')
# with open("data.txt", "r") as file:
#     content = file.read()
# -> UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 42: character maps to <undefined>

# 1. FIX A (Recommended): Explicitly pass encoding="utf-8" to open()
with open("data.txt", "r", encoding="utf-8") as file:
    content = file.read()

# 2. FIX B (pathlib): Pass encoding="utf-8" to Path.read_text()
from pathlib import Path

text = Path("data.txt").read_text(encoding="utf-8")

# 3. FIX C (Pandas): Pass encoding="utf-8" to pd.read_csv()
import pandas as pd

df = pd.read_csv("data.csv", encoding="utf-8")

Key Details & Edge Cases

  • Why 'charmap' appears specifically on Windows: On Linux and macOS, locale.getpreferredencoding() defaults to UTF-8. On Windows, open() without an encoding argument defaults to the active ANSI code page (cp1252 in Western locales, which uses Python’s charmap decoder). Windows-1252 leaves five byte slots completely undefined (0x81, 0x8d, 0x8f, 0x90, 0x9d)—so any UTF-8 multi-byte sequence containing one of those bytes (for example, ” U+201D = E2 80 9D or 🚀 = F0 9F 9A 80) crashes immediately on 0x9d or 0x8f.
  • Enable global UTF-8 Mode on Windows (PYTHONUTF8=1 or -X utf8): If third-party libraries or scripts omit encoding="utf-8" internally, force Python across your entire Windows environment to default to UTF-8 (PEP 540):
    • Command line: python -X utf8 script.py
    • Environment variable (PowerShell): $env:PYTHONUTF8 = "1" (or set PYTHONUTF8=1 permanently in Windows System Environment Variables).
    • Python 3.15+ note: Python 3.15 enables UTF-8 Mode by default on all platforms, including Windows.
  • When the file is UTF-8 with a BOM (\xef\xbb\xbf) or UTF-16 from PowerShell:
    • Files saved by Windows Notepad or Excel as “UTF-8 with BOM” include a leading \ufeff character; open them with encoding="utf-8-sig" so Python strips the BOM cleanly.
    • Files redirected via PowerShell (echo "hi" > out.txt or Out-File) default to UTF-16 LE; open them with encoding="utf-16".
  • Handling mixed or partially corrupted log files (errors="replace"): If a Windows log file contains a mix of valid UTF-8 and stray binary/ANSI bytes that you cannot re-export cleanly, pass encoding="utf-8", errors="replace" (substitutes `` for invalid bytes) or errors="ignore".

Comparison of Fixes for 'charmap' Decode Errors on Windows

Scenario / Cause Recommended Solution Scope Best Used When
Standard UTF-8 text, JSON, or CSV file open(path, "r", encoding="utf-8") Single file call Reading any modern UTF-8 file on Windows (always follow PEP 597).
Third-party script omits encoding= Set PYTHONUTF8=1 or run python -X utf8 script.py Entire Python process Running external tools or legacy scripts on Windows without editing their source.
Windows Excel / Notepad UTF-8 with BOM open(path, "r", encoding="utf-8-sig") Single file call First key or column name starts with \ufeff.
PowerShell > or Out-File output open(path, "r", encoding="utf-16") Single file call File starts with 0xff 0xfe BOM or has null bytes between ASCII characters.
Damaged file with stray invalid bytes open(path, "r", encoding="utf-8", errors="replace") Single file call Parsing noisy logs where skipping/replacing bad bytes is acceptable.