Browse topics

pathlib.Path

Version
3.14
Since
3.4
Review
Draft

Summary#

Path represents a filesystem path as an object. The / operator joins segments, and methods read, write, create and search files.

Syntax#

python
path = Path(directory) / "name.txt"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
path.read_text(encoding="utf-8")
sorted(root.glob("**/*.txt"))

Example#

python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    reports = root / "reports" / "2026"
    reports.mkdir(parents=True, exist_ok=True)
    (reports / "b.txt").write_text("beta\n", encoding="utf-8")
    (reports / "a.txt").write_text("alpha\n", encoding="utf-8")

    for path in sorted(root.glob("**/*.txt")):
        print(path.relative_to(root).as_posix(), path.stem, path.suffix)

    first = reports / "a.txt"
    print(first.read_text(encoding="utf-8").strip())
    print(first.with_suffix(".md").name, first.exists())

Expected output#

Text
reports/2026/a.txt a .txt
reports/2026/b.txt b .txt
alpha
a.md True

Common mistakes#

An absolute segment can reset the path. On POSIX, Path("/srv/data") / "/etc/hosts" is /etc/hosts. A relative path with .. can also leave the intended directory. Validate untrusted names before joining them. glob returns results in no particular order, so sort them when order matters.

Version applicability#

pathlib was added in Python 3.4. The read_text and write_text methods and the exist_ok argument of mkdir require Python 3.5 or later, as does the complete example.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0