Introduction
os.path.join, os.path.exists, os.path.basename — the old way of handling file paths. pathlib (Python 3.4+) replaces all of them with an object-oriented API that’s cleaner, more readable, and cross-platform. In 2026, pathlib is the standard.
The basics
from pathlib import Path
# Create paths
p = Path("data") / "users" / "galvan.json"
print(p) # data/users/galvan.json
print(p.name) # galvan.json
print(p.stem) # galvan
print(p.suffix) # .json
print(p.parent) # data/users
print(p.parents[0]) # data/users
print(p.parents[1]) # data
The / operator joins paths — no more os.path.join.
Path operations
from pathlib import Path
p = Path("data/users/galvan.json")
# Existence
p.exists() # True/False
p.is_file() # True
p.is_dir() # False
# Read/write (convenience methods)
text = p.read_text() # read entire file
data = p.read_bytes() # read as bytes
p.write_text("hello") # write text
p.write_bytes(b"hello") # write bytes
# Append
with p.open("a") as f:
f.write("\nmore data")
read_text() and write_text() are huge quality-of-life improvements over open().
Creating and deleting
from pathlib import Path
# Create directories
Path("data/users").mkdir(parents=True, exist_ok=True)
# Create file
Path("data/users/galvan.json").touch()
# Delete
Path("data/users/galvan.json").unlink() # delete file
Path("data/users").rmdir() # delete empty dir
# Rename/move
Path("old.txt").rename("new.txt")
Path("old.txt").replace("new.txt") # overwrites if exists
Globbing
from pathlib import Path
# Find all Python files
for f in Path(".").glob("**/*.py"):
print(f)
# Find all .json files (non-recursive)
for f in Path("data").glob("*.json"):
print(f)
# rglob = recursive glob (same as glob("**/..."))
for f in Path(".").rglob("*.md"):
print(f)
No more glob.glob + os.path.join.
os.path vs pathlib
| os.path | pathlib |
|---|---|
os.path.join("a", "b") |
Path("a") / "b" |
os.path.exists(p) |
p.exists() |
os.path.isfile(p) |
p.is_file() |
os.path.basename(p) |
p.name |
os.path.splitext(p)[0] |
p.stem |
os.path.splitext(p)[1] |
p.suffix |
os.path.dirname(p) |
p.parent |
os.path.abspath(p) |
p.resolve() |
os.path.expanduser("~") |
Path.home() |
os.getcwd() |
Path.cwd() |
os.listdir(p) |
list(p.iterdir()) |
os.makedirs(p, exist_ok=True) |
p.mkdir(parents=True, exist_ok=True) |
Resolving and normalizing
from pathlib import Path
p = Path("data/../config.json")
print(p) # data/../config.json (not normalized)
print(p.resolve()) # /absolute/path/to/config.json (normalized + absolute)
# Relative path
p = Path("/home/galvan/project/data.json")
print(p.relative_to("/home/galvan")) # project/data.json
resolve() is like os.path.abspath + os.path.normpath.
Working with the current directory
from pathlib import Path
# Current working directory
cwd = Path.cwd()
# Home directory
home = Path.home()
# Script's directory
script_dir = Path(__file__).resolve().parent
# Read a file relative to the script
config = (script_dir / "config.json").read_text()
Path(__file__).resolve().parent is the modern replacement for os.path.dirname(os.path.abspath(__file__)).
Common patterns
Find and process all files
from pathlib import Path
for f in Path("data").rglob("*.csv"):
df = pd.read_csv(f)
process(df)
print(f"Processed {f.name}")
Ensure directory exists
from pathlib import Path
output_dir = Path("output/reports")
output_dir.mkdir(parents=True, exist_ok=True)
(output_dir / "report.txt").write_text("Done!")
Copy files
import shutil
from pathlib import Path
src = Path("source.txt")
dst = Path("backup/source.txt")
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst) # copy2 preserves metadata
Watch for new files
from pathlib import Path
import time
watch_dir = Path("inbox")
seen = set()
while True:
for f in watch_dir.glob("*.json"):
if f not in seen:
process(f)
seen.add(f)
time.sleep(1)
os.path compatibility
pathlib objects work with most functions that expect strings:
from pathlib import Path
import json, csv
p = Path("data.json")
with open(p) as f: # works
data = json.load(f)
with p.open() as f: # better
data = json.load(f)
If a library doesn’t accept Path, convert with str(p) or os.fspath(p).
Common mistakes
- Using
os.pathin new code — pathlib is cleaner and cross-platform. Use it for new projects. - Forgetting
parents=True—mkdir()fails if parent doesn’t exist. Usemkdir(parents=True, exist_ok=True). - Not resolving paths — relative paths can be confusing. Use
.resolve()for absolute paths. - Mixing
strandPath— most libs accept both, but convert withstr()if needed. - Using
globwithout sorting —glob()returns in arbitrary order. Sort if order matters:sorted(Path(".").glob("*.py")).
Key Concepts
Path= object representing a filesystem path/operator = join paths.read_text()/.write_text()= quick file I/O.glob()/.rglob()= find files by pattern.resolve()= absolute, normalized path.mkdir(parents=True, exist_ok=True)= create directories safely
What to Try Next
- Replace
os.pathin your Streamlit app with pathlib. - Use pathlib in your FastAPI backend for file handling.
- Combine with generators for lazy file processing.
- Use
Path.rglobto find all files in a project directory.
FAQ
pathlib vs os.path — which is better?
pathlib is the modern standard: object-oriented, readable, cross-platform. os.path is functional and older. For new code, use pathlib. For legacy codebases, os.path is fine.
Does pathlib work on Windows?
Yes — pathlib handles path separators automatically. Path("a") / "b" produces a\b on Windows and a/b on Unix. No more os.path.join hacks.
Is pathlib slower than os.path?
Negligibly. The overhead is tiny compared to actual I/O. For performance-critical code (millions of path operations), os.path might be marginally faster, but the readability trade-off isn’t worth it.