Skip to course content
Free course

Python Foundations / Module 7 / Paths with pathlib

Module 7 lesson

Paths with pathlib

Unit ID: M07-U01 Estimated active time: 22-30 minutes

A path describes a location

Use pathlib.Path instead of manually joining path strings:

from pathlib import Path

project_dir = Path("module7-work")
source_path = project_dir / "data" / "source_courses.csv"
output_dir = project_dir / "output"

The / operator joins path parts using the operating system's conventions.

Relative and absolute paths

A relative path is interpreted from the current working directory. An absolute path begins from a filesystem root.

print(Path.cwd())
print(source_path.resolve())

Notebooks may start in a different working directory from the script you expect. Inspect Path.cwd() when a relative file cannot be found.

Inspect safely

print(source_path.exists())
print(source_path.is_file())
print(source_path.name)
print(source_path.suffix)

An existing path may be a directory rather than a file. Check the role you require.

Create output folders deliberately

output_dir.mkdir(parents=True, exist_ok=True)

This creates missing parent folders and does not fail merely because the directory already exists. It does not prove that writing every file there is safe.

Avoid hard-coded personal paths

Do not publish code containing paths such as a specific user's desktop directory. Build paths from the supplied project root or a function argument.

Practice

Create a Path for data/source_courses.csv and outputs under output/accepted_courses.json. Print each name, suffix, parent, and resolved location without creating or changing the source file.

Takeaway

Path objects make file locations portable and inspectable. Relative paths still depend on the current working directory, so make the project root explicit. Next, we will read and write text with encodings and context managers.