- Understand absolute and relative paths
- Use the pathlib module for modern path handling
- Build paths that work across operating systems
- Navigate directories programmatically
Working with Paths
Imagine you're giving someone directions to your house. You could say "123 Main Street, Apt 4B, New York, NY 10001" (absolute – complete address from scratch) or "two blocks north, turn left" (relative – from where they are now). File paths work the same way!
Understanding paths is crucial for finding, organizing, and managing files. In this lesson, you'll learn to navigate the file system like a pro, using modern Python tools that work on any operating system.
Understanding Paths
Path Types Comparison
ABSOLUTE PATH: Complete address from root
Windows: C:\Users\Alice\Documents\file.txt
Mac/Linux: /home/alice/documents/file.txt
• Always starts from root (/ or C:\)
• Works from anywhere
• Longer but unambiguous
RELATIVE PATH: Directions from current location
data/file.txt (into 'data' folder)
../other/file.txt (up one level, into 'other')
./file.txt (current directory)
• Depends on current working directory
• Shorter and portable
• Can break if you run from different location
Special Path Symbols
| Symbol | Meaning | Example |
|---|---|---|
. |
Current directory | ./file.txt = file here |
.. |
Parent directory | ../file.txt = file one level up |
~ |
Home directory | ~/Documents (Unix only) |
The pathlib Module
pathlib is the modern, elegant way to work with paths:
Creating Paths
from pathlib import Path
# Create a Path object
current = Path(".") # Current directory
home = Path.home() # User's home directory
documents = Path.home() / "Documents" # Home/Documents
# From string
file_path = Path("data/users.txt")
# Get current working directory
cwd = Path.cwd()
print(cwd) # /Users/alice/project
Joining Paths (The / Operator)
from pathlib import Path
# The elegant way to join paths
base = Path("project")
data = base / "data"
file = data / "users.txt"
print(file) # project/data/users.txt
# Works on ALL operating systems automatically!
# Windows: project\data\users.txt
# Mac/Linux: project/data/users.txt
Why This Matters
Cross-Platform Paths
BAD: Hardcoded separators
path = "data/users/file.txt" # Only works on Mac/Linux
path = "data\\users\\file.txt" # Only works on Windows
GOOD: Using pathlib
path = Path("data") / "users" / "file.txt"
# Works EVERYWHERE!
pathlib automatically uses the correct separator for your OS!
Path Properties and Methods
Getting Path Components
from pathlib import Path
path = Path("/home/alice/documents/report.pdf")
print(path.name) # report.pdf (filename)
print(path.stem) # report (filename without extension)
print(path.suffix) # .pdf (extension)
print(path.parent) # /home/alice/documents (parent directory)
print(path.parts) # ('/', 'home', 'alice', 'documents', 'report.pdf')
Visual Breakdown
Path Components
Path: /home/alice/documents/report.pdf
.parent → /home/alice/documents
.name → report.pdf
.stem → report
.suffix → .pdf
.parts = ('/', 'home', 'alice', 'documents', 'report.pdf')
Checking Path Status
from pathlib import Path
path = Path("some_file.txt")
# Does it exist?
print(path.exists()) # True/False
# What type is it?
print(path.is_file()) # True if it's a file
print(path.is_dir()) # True if it's a directory
# Is it absolute?
print(path.is_absolute()) # True if absolute path
Listing Directory Contents
from pathlib import Path
directory = Path(".")
# List everything in directory
for item in directory.iterdir():
print(item)
# List only files
for item in directory.iterdir():
if item.is_file():
print(f"File: {item}")
# List only directories
for item in directory.iterdir():
if item.is_dir():
print(f"Folder: {item}")
Using glob Patterns
from pathlib import Path
directory = Path(".")
# Find all .txt files
for txt_file in directory.glob("*.txt"):
print(txt_file)
# Find all .py files (including subdirectories)
for py_file in directory.rglob("*.py"): # r = recursive
print(py_file)
# Find files matching pattern
for file in directory.glob("data_*.csv"): # data_01.csv, data_02.csv, etc.
print(file)
Practical Examples
Example 1: Finding Project Files
from pathlib import Path
def find_project_files(project_dir, extension):
"""Find all files with given extension in project."""
project = Path(project_dir)
files = list(project.rglob(f"*{extension}"))
print(f"Found {len(files)} {extension} files:")
for file in files:
# Show relative path from project root
print(f" {file.relative_to(project)}")
return files
find_project_files(".", ".py")
Example 2: Organizing Downloads
from pathlib import Path
def organize_by_extension(source_dir):
"""Organize files into folders by extension."""
source = Path(source_dir)
for file in source.iterdir():
if file.is_file():
# Get extension without the dot
ext = file.suffix.lower()[1:] or "no_extension"
# Create folder for this extension
dest_folder = source / ext
dest_folder.mkdir(exist_ok=True)
# Move file
new_path = dest_folder / file.name
file.rename(new_path)
print(f"Moved {file.name} to {ext}/")
# organize_by_extension("downloads")
Example 3: Safe Path Building
from pathlib import Path
def build_output_path(base_dir, category, filename):
"""Build a safe output path, creating directories as needed."""
base = Path(base_dir)
output_dir = base / "output" / category
# Create all directories in path if they don't exist
output_dir.mkdir(parents=True, exist_ok=True)
return output_dir / filename
# Usage
path = build_output_path("project", "reports", "summary.txt")
print(path) # project/output/reports/summary.txt
# Directories are created automatically!
Key Takeaways
Remember These Points
Use pathlib for modern path handling
from pathlib import Path
Join paths with / operator
Path("folder") / "subfolder" / "file.txt"
Useful properties:
.name (filename), .suffix (extension)
.parent (parent dir), .stem (name without ext)
Check existence with:
.exists(), .is_file(), .is_dir()
Find files with:
.glob("*.txt"), .rglob("*.py") (recursive)
pathlib works on ALL operating systems!
What's Next?
You can navigate paths like a pro! In the next lesson, we'll explore file management – creating directories, copying files, deleting files, and organizing your file system programmatically.
