Always pass encoding="utf-8" explicitly to open() inside a with statement (with open("file.txt", "w", encoding="utf-8") as f: and with open("file.txt", "r", encoding="utf-8") as f:), or use pathlib.Path("file.txt").read_text(encoding="utf-8") and .write_text(..., encoding="utf-8") for concise one-line file operations—because omitting encoding= falls back to the OS locale encoding (such as cp1252 on Windows), causing UnicodeEncodeError or UnicodeDecodeError on non-ASCII text.
Basic Example
from pathlib import Path
text = "Café résumé — مرحبا — 你好 🚀\nSecond line."
# 1. Recommended (streaming / multi-line files): explicit `encoding="utf-8"` with `open()`
with open("notes.txt", mode="w", encoding="utf-8", newline="\n") as f:
f.write(text)
with open("notes.txt", mode="r", encoding="utf-8") as f:
content = f.read()
print(content)
# Output:
# Café résumé — مرحبا — 你好 🚀
# Second line.
# 2. Recommended (concise whole-file read/write): `pathlib.Path`
path = Path("notes_pathlib.txt")
path.write_text(text, encoding="utf-8")
loaded = path.read_text(encoding="utf-8")
Key Details & Edge Cases
- Why omitting
encoding="utf-8"breaks cross-platform code (especially on Windows):- On Linux and macOS,
locale.getencoding()is almost alwaysUTF-8, soopen("f.txt", "w")works by accident. On Windows (unless Python UTF-8 Mode-X utf8/PYTHONUTF8=1is enabled),open()defaults to legacy ANSI code pages likecp1252, raisingUnicodeEncodeError: 'charmap' codec can't encode characterwhen writing emojis, accented letters, or non-Latin scripts.
- On Linux and macOS,
- Handling Windows UTF-8 files that contain a Byte Order Mark (
encoding="utf-8-sig"):- Programs like Windows Notepad, Excel CSV exports, and PowerShell often prepend a 3-byte UTF-8 BOM (
\xef\xbb\xbf) at the start of a file. Reading with standardencoding="utf-8"leaves a hidden"\ufeff"character attached to the first string or CSV column header. Useencoding="utf-8-sig"when reading external files—it automatically strips the BOM if present and behaves identically to"utf-8"if absent (do not use"utf-8-sig"when writing unless a legacy Windows tool explicitly demands a BOM).
- Programs like Windows Notepad, Excel CSV exports, and PowerShell often prepend a 3-byte UTF-8 BOM (
- Gracefully recovering from corrupted bytes (
errors="replace"vs.errors="strict"):- By default (
errors="strict"), a single invalid byte sequence raisesUnicodeDecodeError. When ingesting untrusted logs or legacy files, passerrors="replace"(open("log.txt", encoding="utf-8", errors="replace")) to substitute malformed bytes with the Unicode replacement character `` (\ufffd) instead of crashing.
- By default (
- Preventing double blank lines in CSV files on Windows (
newline=""):- When writing CSV files with Python’s
csvmodule, always pairencoding="utf-8"withnewline=""(open("out.csv", "w", encoding="utf-8", newline="")) so Windows CRLF translation doesn’t insert extra blank lines between rows.
- When writing CSV files with Python’s
- Never mix
"b"binary mode withencoding=:- Passing
encoding="utf-8"with"rb"or"wb"raisesValueError: binary mode doesn't take an encoding argument. Use"r"/"w"/"a"text mode withencoding="utf-8", or encode/decode explicitly (b_data.decode("utf-8")) in binary mode.
- Passing
Comparison of UTF-8 File Reading & Writing Methods in Python
| Method | Strips Leading UTF-8 BOM (\ufeff)? |
Memory Behavior | Best Used When |
|---|---|---|---|
with open(path, "r"/"w", encoding="utf-8") as f: (Recommended) |
No (keeps \ufeff if present) |
Streams line-by-line (for line in f:) |
Large files, incremental writes, csv / json streaming, and general production file I/O. |
open(path, "r", encoding="utf-8-sig") |
Yes (auto-strips BOM if present) | Streams line-by-line | Reading CSVs, configs, or text files exported by Excel, Notepad, or Windows tools. |
Path(path).read_text(encoding="utf-8") / .write_text(..., encoding="utf-8") |
No (pass "utf-8-sig" if needed) |
Loads/writes entire file in memory | Concise one-liners for small-to-medium config files, templates, or scripts. |
open(path, "r", encoding="utf-8", errors="replace") |
No | Streams line-by-line | Parsing messy logs or user uploads that may contain occasional invalid UTF-8 bytes. |
You must log in or register to comment.
