How do you properly read and write UTF-8 encoded files in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you properly read and write UTF-8 encoded files in Python?

message-square
0

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 always UTF-8, so open("f.txt", "w") works by accident. On Windows (unless Python UTF-8 Mode -X utf8 / PYTHONUTF8=1 is enabled), open() defaults to legacy ANSI code pages like cp1252, raising UnicodeEncodeError: 'charmap' codec can't encode character when writing emojis, accented letters, or non-Latin scripts.
  • 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 standard encoding="utf-8" leaves a hidden "\ufeff" character attached to the first string or CSV column header. Use encoding="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).
  • Gracefully recovering from corrupted bytes (errors="replace" vs. errors="strict"):
    • By default (errors="strict"), a single invalid byte sequence raises UnicodeDecodeError. When ingesting untrusted logs or legacy files, pass errors="replace" (open("log.txt", encoding="utf-8", errors="replace")) to substitute malformed bytes with the Unicode replacement character `` (\ufffd) instead of crashing.
  • Preventing double blank lines in CSV files on Windows (newline=""):
    • When writing CSV files with Python’s csv module, always pair encoding="utf-8" with newline="" (open("out.csv", "w", encoding="utf-8", newline="")) so Windows CRLF translation doesn’t insert extra blank lines between rows.
  • Never mix "b" binary mode with encoding=:
    • Passing encoding="utf-8" with "rb" or "wb" raises ValueError: binary mode doesn't take an encoding argument. Use "r"/"w"/"a" text mode with encoding="utf-8", or encode/decode explicitly (b_data.decode("utf-8")) in binary mode.

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.