How do you resolve "UnicodeEncodeError: 'charmap' codec can't encode characters" in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you resolve "UnicodeEncodeError: 'charmap' codec can't encode characters" in Python?

message-square
0

Explicitly pass encoding="utf-8" when opening files (open("out.txt", "w", encoding="utf-8")) or enable Python UTF-8 Mode (python -X utf8 / PYTHONUTF8=1) so Windows does not default to legacy single-byte code pages (cp1252 / charmap), and call sys.stdout.reconfigure(encoding="utf-8") when printing Unicode characters (emojis, accented text, non-Latin scripts) to a legacy Windows console.

Basic Example

import sys

text = "Invoice Total: €150.00 — Paid ✅"

# 1. Recommended for file writes: Always pass `encoding="utf-8"` explicitly
with open("receipt.txt", mode="w", encoding="utf-8") as f:
    f.write(text + "\n")

# 2. Recommended for console / stdout printing on Windows:
#    Reconfigure stdout/stderr to UTF-8 (Python 3.7+) before printing Unicode
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
print(text)

# 3. Fallback when forced to write to a legacy cp1252 file (replaces unmappable chars with "?"):
with open("legacy_ansi.txt", mode="w", encoding="cp1252", errors="replace") as f:
    f.write(text + "\n")  # Writes: Invoice Total: €150.00 — Paid ?

Key Details & Edge Cases

  • Why this error happens primarily on Windows (cp1252 / charmap):
    • On Linux and macOS, locale.getpreferredencoding() defaults to UTF-8, which can encode all 1.1 million Unicode code points.
    • On Western Windows installations, open("file.txt", "w") without an explicit encoding= defaults to cp1252 (charmap), which only maps 256 byte values—so writing any character outside Western European Latin (such as emojis ✅, arrows →, math symbols ∑, or Urdu/Arabic/CJK scripts) immediately raises UnicodeEncodeError: 'charmap' codec can't encode character ... in position ...: character maps to <undefined>.
  • Fix an entire script or CI environment globally with PYTHONUTF8=1 (-X utf8):
    • Running python -X utf8 script.py (or setting the environment variable PYTHONUTF8=1 in Windows System Environment Variables / PowerShell $env:PYTHONUTF8 = "1") forces Python’s open(), sys.stdout, and sys.stderr to default to UTF-8 everywhere without changing existing code. (Note: Python 3.15+ makes UTF-8 Mode the default on Windows.)
  • Redirecting print() output to a file on Windows (python script.py > out.txt):
    • Even if Windows Terminal displays UTF-8 interactively, redirecting stdout to a file (> out.txt) or pipe in older Windows builds can switch sys.stdout.encoding back to cp1252 unless you run python -X utf8 script.py > out.txt or call sys.stdout.reconfigure(encoding="utf-8").
  • CSV exports for Microsoft Excel on Windows (encoding="utf-8-sig"):
    • If you write a UTF-8 CSV file with open("data.csv", "w", encoding="utf-8", newline="") or df.to_csv("data.csv", encoding="utf-8"), older desktop Excel versions on Windows may misread UTF-8 characters as garbled Latin-1 unless you use encoding="utf-8-sig" (which prepends a UTF-8 Byte Order Mark so Excel auto-detects UTF-8).
  • Avoid errors="ignore" unless silent character deletion is acceptable:
    • errors="ignore" silently drops unencodable characters ("100 €" $\rightarrow$ "100 "), which can corrupt prices, identifiers, or text meaning. Prefer encoding="utf-8" whenever possible, or errors="replace" (?) / errors="xmlcharrefreplace" (&#9989;) when constrained to legacy encodings.

Comparison of Fixes for UnicodeEncodeError: 'charmap' codec

Fix / Approach Scope Preserves All Unicode Characters? Requires Modifying Source Code? Best Used When
open(path, "w", encoding="utf-8") (Recommended) Per file handle Yes Yes (add encoding="utf-8") Writing text, JSON, logs, or CSV files in cross-platform Python code (PEP 597 best practice).
python -X utf8 / PYTHONUTF8=1 (Recommended for legacy scripts) Entire Python process / OS environment Yes No Fixing third-party scripts, CI pipelines, or Windows stdout redirects (> out.txt) globally.
sys.stdout.reconfigure(encoding="utf-8") Standard output / error streams (Python 3.7+) Yes Yes (1 line at startup) CLI tools printing emojis, box-drawing tables, or multilingual text to Windows terminals.
errors="replace" / errors="xmlcharrefreplace" Single file or .encode() call No (substitutes ? or HTML entities) Yes Integrating with legacy Windows systems that strictly require cp1252 / ASCII files.