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 needThe / 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 directoryListing 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 tooThe glob() method supports wildcard patterns. * matches any filename. ** matches any number of subdirectories.
Getting file information
Path objects expose useful properties:
| Property | Returns |
|---|---|
path.name | Filename with extension: "report.txt" |
path.stem | Filename without extension: "report" |
path.suffix | Extension: ".txt" |
path.parent | Parent 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 directoriesUse pathlib for path manipulation. Use os for system operations like creating directories or getting environment variables.
Instructions
Explore the filesystem with pathlib and os.
- Import
Pathfrompathliband import theosmodule. - Create a variable named
currentand assign itPath.cwd(). - Call
print()withf"Current directory: {current}". - Create a variable named
homeand assign itPath.home(). - Call
print()withf"Home directory: {home}". - Create a variable named
test_pathand assign itPath("example.txt"). - Call
print()withf"Name: {test_path.name}". - Call
print()withf"Stem: {test_path.stem}". - Call
print()withf"Suffix: {test_path.suffix}".
# Step 1: Import Path from pathlib and import os # Step 2: Get current working directory # Step 3: Print current directory # Step 4: Get home directory # Step 5: Print home directory # Step 6: Create a test path for "example.txt" # Step 7: Print the name # Step 8: Print the stem # Step 9: Print the suffix
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding