pathlib cheat sheet: files and folders in Python
pathlib.Path is the modern way to build paths, read and write files, and list or search folders in Python. This page lists the operations you need most.
Older Python code glues paths together with strings and os.path.join. The pathlib module, part of the standard library, wraps a path in a Path object instead. You join parts with /, ask the object questions like .exists(), and read or write the file directly. The same code works on Windows, macOS and Linux because Path uses the right separator for the system.
from pathlib import Path
Building paths
Path.home() # your home folder
Path.cwd() # current working directory
Path(__file__).resolve().parent # folder of the running script
p = Path("reports") / "2026" / "summary.final.csv"
p.name # 'summary.final.csv'
p.stem # 'summary.final'
p.suffix # '.csv'
p.suffixes # ['.final', '.csv']
p.parent # Path('reports/2026')
p.parts # ('reports', '2026', 'summary.final.csv')
p.with_suffix(".json") # reports/2026/summary.final.json
p.with_name("other.csv") # reports/2026/other.csv
p.with_stem("summary.v2") # reports/2026/summary.v2.csv
Tip: to open files that sit next to your script, build paths from Path(__file__).resolve().parent, not from the current directory. The current directory depends on where the user ran the command from.
Reading and writing
f = Path("output/logs/hello.txt")
f.parent.mkdir(parents=True, exist_ok=True) # like mkdir -p
f.write_text("line one\nline two\n", encoding="utf-8")
text = f.read_text(encoding="utf-8")
lines = text.splitlines()
with f.open("a", encoding="utf-8") as fh: # append, or stream big files
fh.write("line three\n")
Path("data.bin").write_bytes(b"\x00\x01")
Path("data.bin").read_bytes()
Always pass encoding="utf-8" for text. Without it Python uses the platform default, which on some Windows setups is not UTF-8, and files with accents or emoji then fail to load.
Checking and inspecting
f.exists(), f.is_file(), f.is_dir()
f.stat().st_size # size in bytes
f.stat().st_mtime # last modified, as a timestamp
f.resolve() # absolute path, symlinks resolved
f.relative_to("output") # Path('logs/hello.txt')
Listing and searching
folder = Path("output")
for child in folder.iterdir(): # direct children only
print(child)
sorted(Path(".").glob("*.py")) # matching files in one folder
sorted(Path(".").rglob("*.txt")) # recursive search
[p for p in folder.rglob("*") if p.is_file()] # every file below
iterdir and glob return items in no particular order. Wrap them in sorted() when the order matters, for example when output must be reproducible.
Moving, copying and deleting
import shutil
new = f.rename(f.with_name("renamed.txt")) # move or rename, returns new Path
shutil.copy2(new, new.with_name("copy.txt")) # copy file with metadata
shutil.copytree("src_dir", "backup_dir") # copy a whole folder
new.unlink() # delete a file
Path("maybe.txt").unlink(missing_ok=True)
Path("empty_dir").rmdir() # only works on empty folders
shutil.rmtree("some_dir") # deletes a folder and EVERYTHING in it
Deletions with unlink and shutil.rmtree are permanent, not a move to the trash. In automation scripts, print what would be deleted first (a “dry run”) and only delete when a flag such as --yes is given.
Converting
str(p) # plain string, for libraries that want one
p.as_posix() # always forward slashes, useful in URLs and configs
os.fspath(p) # what most APIs call internally (import os first)
Most of the standard library and popular packages accept Path objects directly, so converting to str is rarely needed today.
See also
- 0004 Logging instead of print The logging module gives every message a level, a timestamp and a destination you can change without editing code. It is the… Intermediate · Concept · Any system Article Files & automation 15 Oct 2026
- 0009 CSV to JSON converter A small command-line tool that turns a CSV file into a JSON array of objects, with optional number detection, custom delimiters and… Beginner · How-to · Any system Script CSV & JSON · Files & automation 15 Oct 2026
- 0010 Find duplicate files by content Scans folders and lists files with identical content, using file size first and SHA-256 hashes second. It is read-only and only reports… Intermediate · How-to · Any system Script Files & automation 15 Oct 2026
- 0074 pandas basics: read a CSV, filter rows and summarize with groupby Load a CSV into a pandas DataFrame, inspect it, filter rows with conditions, and compute totals per group, with the SQL equivalent… Intermediate · How-to · Any system Article Data analysis · Files & automation 15 Oct 2026
- 0075 CSV to JSON converter (Python, standard library) Convert any CSV file with a header row into a JSON array or JSON Lines. Handles quoted fields, a byte order mark,… Beginner · How-to · Any system Script CSV & JSON · Files & automation 15 Oct 2026
- 0084 Tiny JSON echo server for testing HTTP clients A standard-library Python server that echoes back the method, path, query, headers, and body of every request, and can return any status… Intermediate · How-to · Any system Script Files & automation · Making requests 15 Oct 2026
Repos in the wild
- Requests: HTTP for humans psf/requests Requests is the classic Python library for calling web APIs and downloading pages, with a simple API for GET and POST requests, headers, JSON and sessions. GitHub
History
Every saved edit is kept. The plot on the sleeve draws one line per edit. Open any edit to see exactly what changed.
- commitpedia-admin +4,027 chars