Modern Filesystem Management with Pathlib
Manage files, directories, and cross-platform file paths using Python's modern object-oriented pathlib module, replacing legacy os.path.
If you have ever used computers with different operating systems, you have probably run into their clashing conventions for file paths:
- macOS and Linux separate folders with a forward slash:
/home/alex/projects/app.py - Windows separates folders with a backslash:
C:\Users\alex\projects\app.py
In older Python code, developers treated file paths as plain strings and relied on functions from the legacy os.path module (like os.path.join(), os.path.exists(), os.path.basename()). Gluing strings together was cumbersome and frequently introduced subtle cross-platform bugs.
In modern Python (3.4+), the standard library includes pathlibโan object-oriented module that represents filesystem paths as intelligent objects rather than dumb text strings.
1. Creating Paths with the Slash Operator (/)
The core object in pathlib is Path.
Instead of concatenating strings with plus signs, pathlib overloads the division operator (/) so you can construct paths naturally:
from pathlib import Path
# Path to the current working directory
current_folder = Path.cwd()
# Path to the user's home folder (e.g. /home/alex or C:\Users\alex)
home_folder = Path.home()
# Compose a sub-path using the forward slash operator:
config_path = current_folder / "config" / "settings.json"
print("Composed path:", config_path)
No matter what operating system your code runs on, pathlib automatically uses the correct operating system separator!
2. Inspecting Path Components
A Path object gives you instant access to every part of a file location:
from pathlib import Path
p = Path("/home/alex/reports/quarterly_earnings.xlsx")
print("Full path: ", p)
print("Filename: ", p.name) # quarterly_earnings.xlsx
print("Filename stem: ", p.stem) # quarterly_earnings (no extension!)
print("File extension: ", p.suffix) # .xlsx
print("Parent directory: ", p.parent) # /home/alex/reports
print("Grandparent dir: ", p.parent.parent) # /home/alex
3. Querying the Filesystem
You can query a Path object directly to inspect physical files on disk:
from pathlib import Path
target = Path("sample.txt")
# 1. Does the path exist?
if target.exists():
print("Found target on disk!")
# 2. Is it a regular file or a directory?
if target.is_file():
print(f"File size: {target.stat().st_size} bytes")
elif target.is_dir():
print("Target is a folder.")
else:
print("Path does not exist on disk.")
4. Convenient Quick File I/O: .read_text() & .write_text()
For small configuration files and quick scripts, pathlib eliminates the need to write multi-line with open(...) blocks:
from pathlib import Path
note_file = Path("quick_note.txt")
# Write text directly in one line:
note_file.write_text("Hello from Pathlib!\n", encoding="utf-8")
# Read text directly in one line:
content = note_file.read_text(encoding="utf-8")
print("File content:\n", content)
Both .read_text() and .write_text() automatically open the file, perform the operation, and close it cleanly behind the scenes.
5. Creating Folders Safely with .mkdir()
When preparing an output folder for logs, exports, or data downloads, creating nested folders with os.makedirs was error-prone. With pathlib, it is a clean one-liner:
from pathlib import Path
export_dir = Path("build") / "assets" / "images"
# parents=True: creates all parent folders (build/ and assets/) if missing
# exist_ok=True: does NOT raise an error if the directory already exists!
export_dir.mkdir(parents=True, exist_ok=True)
print(f"Directory ready: {export_dir.resolve()}")
6. Searching and Filtering with Globbing
Need to find all .py files in a repository, or all .csv files in a data folder? pathlib includes powerful pattern matching via globbing:
from pathlib import Path
project_root = Path.cwd()
# Find all Python files in the current folder:
print("Python scripts in current directory:")
for script in project_root.glob("*.py"):
print(f" - {script.name}")
# Recursively search all subdirectories using .rglob():
print("\nAll Markdown files in entire project:")
for md_file in project_root.rglob("*.md"):
print(f" - {md_file.relative_to(project_root)}")
Summary & Stage 8 Capstone
Congratulations on completing Stage 8: Files & Operating System! You now know how to:
- Safely read and stream files using with open() context managers.
- Serialize and exchange web payloads and spreadsheets with json-csv.
- Navigate, create, and search folders cross-platform using Pathlib.
With foundational data structures, functions, error handling, and file systems under your belt, it is time to step into modern software architecture: Object-Oriented Programming (OOP) in Stage 9, starting with classes.