Working with File Paths (os, pathlib)
Use os.path and pathlib to work with file paths, directories, and file system operations in a cross-platform way.
15 min•By Priygop Team•Updated 2026
File Paths
File Paths
import os
from pathlib import Path
# os.path (traditional)
print(os.getcwd()) # current directory
print(os.path.exists(".")) # True
print(os.path.join("folder", "file.txt"))
# pathlib (modern, recommended!)
p = Path(".")
print(f"Current: {p.resolve()}")
# Path operations
readme = Path("README.md")
print(f"Name: {readme.name}")
print(f"Stem: {readme.stem}") # README
print(f"Suffix: {readme.suffix}") # .md
print(f"Parent: {readme.parent}") # .
# Building paths
data_dir = Path("data")
csv_file = data_dir / "users.csv" # Path joining with /
print(f"Path: {csv_file}")
# Listing directory contents
current = Path(".")
print("\nFiles in current dir:")
for item in sorted(current.iterdir()):
icon = "📁" if item.is_dir() else "📄"
print(f" {icon} {item.name}")
# glob — find files by pattern
# list(Path(".").glob("*.py")) # all .py files
# list(Path(".").rglob("*.txt")) # recursive searchTip
Tip
Use pathlib.Path for modern path handling. Path('dir') / 'file.txt' is cleaner than os.path.join('dir', 'file.txt').
Diagram
Loading diagram…
Everything in Python is an object — use type() to check
Common Mistake
Warning
Hardcoding path separators (/ or \) breaks cross-platform code. Use Path or os.path.join for portable paths.
Practice Task
Note
(1) List all .py files in a directory. (2) Create nested directories with mkdir(parents=True). (3) Check if a path is file or directory.