Pass encoding="utf-8" explicitly to open() inside a with context manager (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 whole-file operations—never omit encoding=, because Python otherwise falls back to the OS locale encoding (such as cp1252 on Windows), which triggers UnicodeEncodeError or UnicodeDecodeError on non-ASCII characters.
Basic Example
from pathlib import Path
content = "Café résumé — مرحبا — 你好 🚀\nLine two."
# 1. Recommended (streaming / line-by-line I/O): explicit `encoding="utf-8"` with `open()`
with open("sample.txt", mode="w", encoding="utf-8", newline="\n") as f:
f.write(content)
with open("sample.txt", mode="r", encoding="utf-8") as f:
for line in f:
print(line.rstrip("\n"))
# Output:
# Café résumé — مرحبا — 你好 🚀
# Line two.
# 2. Recommended (concise whole-file read/write): `pathlib.Path`
file_path = Path("sample_pathlib.txt")
file_path.write_text(content, encoding="utf-8")
loaded_text = file_path.read_text(encoding="utf-8")
Key Details & Edge Cases
- Why omitting
encoding="utf-8"causes platform-specific bugs (PEP 597):- On macOS and most Linux distributions, the default locale encoding is already
UTF-8, masking missingencoding=arguments until code runs on Windows. On Windows (unless Python UTF-8 Mode-X utf8/PYTHONUTF8=1is active),open()defaults to legacy code pages likecp1252, raisingUnicodeEncodeError: 'charmap' codec can't encode characterwhen writing emojis or non-Latin text.
- On macOS and most Linux distributions, the default locale encoding is already
- Reading files saved with a UTF-8 Byte Order Mark (
encoding="utf-8-sig"):- Tools such as Excel CSV exports, Windows Notepad, and PowerShell frequently prepend a 3-byte UTF-8 BOM (
\xef\xbb\xbf). Reading with standardencoding="utf-8"leaves an invisible"\ufeff"character at the start of the first line (breaking JSON parsers or the first CSV header name). Useencoding="utf-8-sig"when reading external files—it strips the BOM automatically if present and reads normal UTF-8 identically if absent. Keepencoding="utf-8"when writing so you don’t emit unnecessary BOM bytes.
- Tools such as Excel CSV exports, Windows Notepad, and PowerShell frequently prepend a 3-byte UTF-8 BOM (
- Handling malformed or mixed-encoding bytes gracefully (
errors=):- By default (
errors="strict"), any invalid UTF-8 byte raisesUnicodeDecodeError. When processing untrusted logs or user uploads, passerrors="replace"(open("app.log", encoding="utf-8", errors="replace")) to replace bad bytes with `` (\ufffd) instead of crashing.
- By default (
- CSV files on Windows (
newline=""):- Always combine
encoding="utf-8"withnewline=""(open("data.csv", "w", encoding="utf-8", newline="")) when using Python’scsvmodule so universal newline translation does not insert extra blank lines between rows on Windows.
- Always combine
- Text mode vs. binary mode (
"b"):- Never pass
encoding=with"rb"or"wb"(ValueError: binary mode doesn't take an encoding argument). Either open in text mode ("r"/"w"/"a") withencoding="utf-8", or read rawbytesin"rb"mode and callraw_bytes.decode("utf-8").
- Never pass
Comparison of UTF-8 File I/O Methods in Python
| Method | Auto-Strips UTF-8 BOM (\ufeff)? |
Memory Footprint | Best Used When |
|---|---|---|---|
with open(path, "r"/"w", encoding="utf-8") as f: (Recommended) |
No (preserves \ufeff if present) |
$O(1)$ streaming (line-by-line) | Large files, incremental writes, json.load/dump, and csv I/O (with newline=""). |
open(path, "r", encoding="utf-8-sig") |
Yes (strips leading BOM if present) | $O(1)$ streaming | Reading CSVs, configs, or text files exported by Windows apps (Excel, Notepad, PowerShell). |
Path(path).read_text(encoding="utf-8") / .write_text(..., encoding="utf-8") |
No (supports "utf-8-sig" if passed) |
Loads/writes entire file in RAM | Concise one-liners for small-to-medium config files, templates, or scripts. |
open(path, "r", encoding="utf-8", errors="replace") |
No | $O(1)$ streaming | Parsing noisy log files or external text streams that may contain occasional invalid bytes. |
You must log in or register to comment.
