os and pathlib

Navigate the filesystem, list files, and check paths in Python

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Why your code needs to understand the filesystem

Many programs work with files — reading data, saving results, organizing downloads. To do this, your code needs to find files, check if they exist, and build file paths.

Python provides two modules for filesystem work: os and pathlib. Both do similar things, but pathlib is the modern approach. It treats file paths as objects instead of plain strings, which makes code cleaner and less error-prone.

Building paths with pathlib

The Path class from pathlib creates path objects:

from pathlib import Path

home = Path.home()              # Your home directory
docs = home / "Documents"       # Join paths with /
file = docs / "report.txt"      # Chain as many as you need

The / operator joins path segments. This reads naturally and avoids bugs from manually concatenating strings with slashes.

Checking what exists

Before working with a file, check that it exists:

path = Path("data")

path.exists()     # True if the path exists (file or directory)
path.is_file()    # True only if it's a file
path.is_dir()     # True only if it's a directory

Listing directory contents

iterdir() returns every item in a directory. Pair it with a list comprehension to filter:

data = Path("data")

all_items = list(data.iterdir())           # Everything in data/
py_files = list(data.glob("*.py"))         # Only .py files
all_py = list(data.glob("**/*.py"))        # .py files in subdirectories too

The glob() method supports wildcard patterns. * matches any filename. ** matches any number of subdirectories.

Getting file information

Path objects expose useful properties:

PropertyReturns
path.nameFilename with extension: "report.txt"
path.stemFilename without extension: "report"
path.suffixExtension: ".txt"
path.parentParent directory

The os module

os provides lower-level system operations:

import os

os.getcwd()            # Current working directory (as string)
os.listdir("data")     # List contents (as list of strings)
os.makedirs("a/b/c", exist_ok=True)  # Create nested directories

Use pathlib for path manipulation. Use os for system operations like creating directories or getting environment variables.

Instructions

Explore the filesystem with pathlib and os.

  1. Import Path from pathlib and import the os module.
  2. Create a variable named current and assign it Path.cwd().
  3. Call print() with f"Current directory: {current}".
  4. Create a variable named home and assign it Path.home().
  5. Call print() with f"Home directory: {home}".
  6. Create a variable named test_path and assign it Path("example.txt").
  7. Call print() with f"Name: {test_path.name}".
  8. Call print() with f"Stem: {test_path.stem}".
  9. Call print() with f"Suffix: {test_path.suffix}".

Next Chapter →