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 toUTF-8, which can encode all 1.1 million Unicode code points. - On Western Windows installations,
open("file.txt", "w")without an explicitencoding=defaults tocp1252(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 raisesUnicodeEncodeError: 'charmap' codec can't encode character ... in position ...: character maps to <undefined>.
- On Linux and macOS,
- Fix an entire script or CI environment globally with
PYTHONUTF8=1(-X utf8):- Running
python -X utf8 script.py(or setting the environment variablePYTHONUTF8=1in Windows System Environment Variables / PowerShell$env:PYTHONUTF8 = "1") forces Python’sopen(),sys.stdout, andsys.stderrto default to UTF-8 everywhere without changing existing code. (Note: Python 3.15+ makes UTF-8 Mode the default on Windows.)
- Running
- 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 switchsys.stdout.encodingback tocp1252unless you runpython -X utf8 script.py > out.txtor callsys.stdout.reconfigure(encoding="utf-8").
- Even if Windows Terminal displays UTF-8 interactively, redirecting stdout to a file (
- 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="")ordf.to_csv("data.csv", encoding="utf-8"), older desktop Excel versions on Windows may misread UTF-8 characters as garbled Latin-1 unless you useencoding="utf-8-sig"(which prepends a UTF-8 Byte Order Mark so Excel auto-detects UTF-8).
- If you write a UTF-8 CSV file with
- 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. Preferencoding="utf-8"whenever possible, orerrors="replace"(?) /errors="xmlcharrefreplace"() 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. |
You must log in or register to comment.
