pathlib and files

The modern way to work with file paths and read or write files.

Also called: open(), with statement, context manager, Path

Domain
Languages
Source
General
Language
Python

In plain English

with closes the file automatically, even after an error.

Example

Path("exports").glob("*.csv") finds every export file.

In code

from pathlib import Path

root = Path("resources/lexikon")
for md in root.glob("*/*.md"):
    text = md.read_text(encoding="utf-8")

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("done\n")

Learn more

Related terms

Added 2026-11-30 · Last reviewed 2026-11-30