Q&A library Python

How do I work with file paths using pathlib in Python?

Python Intermediate filespathlibpaths

Short answer

Build paths with the slash operator on Path objects, and read, write, glob and inspect files through Path methods. It is clearer and more portable than joining strings or using os.path.

The short version

Create a Path and join parts with the / operator, then use its methods to read, write, list and inspect files. pathlib replaces the older string-joining and os.path functions with a single object-oriented interface that reads clearly and handles platform differences for you.

Building paths

from pathlib import Path

p = Path("/tmp") / "reports" / "sales.txt"
print(p)          # /tmp/reports/sales.txt
print(p.name)     # sales.txt
print(p.suffix)   # .txt
print(p.parent)   # /tmp/reports

The / operator joins path parts using the correct separator for the operating system, so the same code works on Windows and Linux without manual slashes.

Reading and writing

For small files, Path has convenience methods that open, read or write, and close in one call.

Path("notes.txt").write_text("hello")
content = Path("notes.txt").read_text()

For larger files, p.open() gives you a normal file object to use in a with block, just like the built-in open.

Listing and globbing

glob finds matching files, and rglob searches subdirectories too.

for csv in Path("data").glob("*.csv"):
    print(csv.name)

for csv in Path("data").rglob("*.csv"):   # recursive
    print(csv)

This is the tidy way to process every file of a type in a folder, replacing the older glob module.

Checking existence and type

p.exists()     # does it exist
p.is_file()    # is it a regular file
p.is_dir()     # is it a directory

These read naturally and return booleans, so they slot straight into conditions.

Creating folders

mkdir makes a directory, and the arguments handle the common cases safely.

Path("output/reports").mkdir(parents=True, exist_ok=True)

parents=True creates any missing intermediate folders, and exist_ok=True stops it raising if the folder already exists, which together avoid the usual boilerplate.

Why prefer pathlib over os.path

The old style mixes string joining (os.path.join) with separate functions (os.path.exists, os.path.basename), so the path bounces between being a string and being passed to functions. pathlib keeps everything on one object, so p.parent.parent / "other.txt" reads clearly. It is the recommended modern approach, and most libraries now accept Path objects directly.

Converting to a string when needed

A few older functions still expect a plain string. Wrap the path in str() at that boundary, though this is increasingly rare as libraries adopt Path support.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project