← Knowledge Base
PythonReference note1 min read · updated 2026-11-27

Python: files, paths and JSON

Read and write text safely with pathlib, encodings and the json module.

pythonfilesjson
from pathlib import Path
import json

p = Path("data") / "notes.txt"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("héllo\n", encoding="utf-8")        # always state the encoding
text = p.read_text(encoding="utf-8")

with open("big.log", encoding="utf-8") as f:     # stream a large file line by line
    for line in f:
        if "ERROR" in line:
            print(line.rstrip())

data = {"name": "srv", "ports": [80, 443]}
Path("cfg.json").write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
cfg = json.loads(Path("cfg.json").read_text(encoding="utf-8"))

On Windows the default encoding is not always UTF-8, so passing encoding="utf-8" avoids garbled characters (for example Romanian diacritics). Use with so files are closed even on errors.