brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's Path.read_text and write_text replace the open and with boilerplate

Python
~/tips/tip-python-pathlib-read-write-text

from pathlib import Path

Read or write a whole small file in one line with pathlib.

For small files I see little need for with open(...) as f:. A Path object can read or write the whole thing in one call.

from pathlib import Path

cfg = Path("settings.ini")
text = cfg.read_text(encoding="utf-8")
cfg.write_text(text.replace("debug = true", "debug = false"), encoding="utf-8")

read_text opens the file, reads it all and closes it again. write_text does the same in the other direction and replaces whatever was in the file. There are read_bytes and write_bytes for images and other binary data.

I’d always pass encoding="utf-8". Without it Python uses the platform default, which is UTF-8 on Linux and macOS but has been something else on Windows, and that’s how a script breaks on the first accented character on someone else’s machine.

Two limits to keep in mind. The whole file goes into memory, so for a multi gigabyte log I’d still loop over lines with open(). And write_text isn’t atomic: if the script dies halfway, the file can be left half written. For an important config, write to a temporary file next to it first and then move it into place with Path.replace().

Further reading: pathlib Path.read_text, pathlib Path.write_text

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link