01 / 20

Python pathlib

Learn to navigate and manipulate file system paths the Pythonic way: using objects instead of fragile strings.

Python

What Is a Path?

A path is the address of a file or folder on your computer. It tells the operating system exactly where to look: which drive, which folders, and which file name.

home student projects app.py /home/student/projects/app.py Each segment is a folder (or file) in the hierarchy

The Old Way: String Paths

Before pathlib, Python developers used raw strings and the os.path module. This works, but it is clunky, error-prone, and looks different on Windows versus Mac/Linux.

import os # Building a path the old way base = "/home/student" folder = "projects" filename = "app.py" full = os.path.join(base, folder, filename) # "/home/student/projects/app.py"

Enter pathlib

pathlib is a built-in Python module (since Python 3.4) that treats paths as objects instead of strings. This means paths have methods and properties you can call directly: no more juggling os.path functions.

from pathlib import Path # Building a path the new way full = Path("/home/student") / "projects" / "app.py"

The Core Class: Path

Path PurePath String logic only (no disk access) Concrete Path Talks to the file system (read, write, check) .parent .name .suffix .stem .parts .exists() .mkdir() .read_text() .iterdir() Path() auto-selects the right type for your OS

Strings vs Path Objects

String + os.path pathlib.Path
Join paths os.path.join(a, b) a / b
Get filename os.path.basename(p) p.name
Get extension os.path.splitext(p)[1] p.suffix
Check exists os.path.exists(p) p.exists()
Read file open(p).read() p.read_text()
Cross-platform Manual care needed Automatic

Anatomy of a Path Object

/home/student/projects/report.txt .parent /home/student/projects .name report.txt .stem report .suffix .txt .parts → ('/', 'home', 'student', 'projects', 'report.txt')

How to Apply pathlib

1
Import Path. Write from pathlib import Path at the top of your script.
2
Create a Path object. Pass a string or use the / operator to build it piece by piece.
3
Inspect properties. Use .name, .suffix, .parent, .stem, or .parts to examine segments.
4
Interact with the file system. Call methods like .exists(), .mkdir(), .read_text(), or .iterdir().
5
Stay cross-platform. Never hard-code slashes. Let pathlib handle the separator.

Essential Properties

.name
The final component: file name with extension.
.stem
File name without its extension.
.suffix
The file extension, including the dot.
.parent
The directory containing this path.
.parts
A tuple of every segment from root to name.
p = Path("/home/student/report.txt") p.name # 'report.txt' p.stem # 'report' p.suffix # '.txt' p.parent # PosixPath('/home/student')

Joining Paths with /

The / operator is pathlib's signature move. It creates a new Path by appending segments, automatically using the correct separator for your OS.

from pathlib import Path base = Path("/home/student") # Join with the / operator project = base / "projects" / "science" # PosixPath('/home/student/projects/science') readme = project / "README.md" # PosixPath('/home/student/projects/science/README.md')

Useful Methods

.exists()
Returns True if the path points to an existing file or directory.
.mkdir()
Creates the directory. Pass parents=True to create parent dirs too.
.iterdir()
Yields each item inside a directory as a Path object.
.read_text()
Reads the entire file and returns its contents as a string.
.write_text()
Writes a string to the file, creating it if needed.
.glob()
Searches for files matching a pattern like "*.py".

Example 1: Inspecting a Path

from pathlib import Path p = Path("/Users/alex/photos/vacation.jpg") print(p.name) # vacation.jpg print(p.stem) # vacation print(p.suffix) # .jpg print(p.parent) # /Users/alex/photos print(p.parts) # ('/', 'Users', 'alex', 'photos', 'vacation.jpg')

Example 2: Building and Checking

from pathlib import Path # Build a path to a config file config = Path.home() / ".config" / "myapp" / "settings.json" # Check if it exists if config.exists(): data = config.read_text() print("Loaded config!") else: # Create parent directories if missing config.parent.mkdir(parents=True, exist_ok=True) config.write_text("{}")

Example 3: Globbing for Files

from pathlib import Path project = Path("my_project") # Find all Python files in the project for py_file in project.glob("*.py"): print(py_file.name) # Recursively find ALL .py files in subdirectories too for py_file in project.rglob("*.py"): print(py_file)

Common Mistakes

✕ String Concatenation
Using "folder" + "/" + "file" instead of the / operator. This breaks on Windows and is harder to read.
✕ Forgetting parents=True
Calling .mkdir() when parent directories do not exist throws FileNotFoundError. Add parents=True.
✕ Mixing Strings and Paths
Passing a Path object to a function that expects a string without converting. Use str(path) if needed.

Question 1 of 5

What does the / operator do when used between two Path objects (or a Path and a string)?

Question 2 of 5

Given p = Path("/data/logs/error.log"), what does p.stem return?

Question 3 of 5

Which method would you use to find all .csv files in a directory and its subdirectories?

Question 4 of 5

What happens if you call p.mkdir() and a parent directory in the path does not exist?

Question 5 of 5

Which of the following is a key advantage of pathlib over os.path?