pathlib
cheat sheet
Python’s pathlib at a glance: build and split paths, read and write files, glob and walk directories, copy, move and delete, plus the os.path mapping.
- Version
- v3.15.2
- Snippets
- 91
- Sections
- 10
Version notes · pathlib 3.15.2
- 3.15 reads and writes text as UTF-8 by default (PEP 686), whatever the OS locale.
- 3.15 adds
mkdir(parents=True, parent_mode=0o755)and removesPurePath.is_reserved(). - 3.14 added
copy(),copy_into(),move(),move_into()and the cachedp.info. - 3.13 added
full_match()andPath.from_uri(). 3.12 addedwalk()andrelative_to(walk_up=True).
Paths as objects instead of strings: join them with /, ask them questions, and read, write, list, copy or delete what they point to.
Join with /
Path("a") / "b" / "c.txt"
Cross-platform
POSIX and Windows paths
Stdlib
nothing to install
Copy & move
built in since 3.14
Quick start
from pathlib import Pathout = Path("build") / "report.txt"out.parent.mkdir(parents=True, exist_ok=True)out.write_text("hello\n")print(sorted(p.name for p in Path(".").glob("*.py")))- Import
- Join with
/ - Join with arguments
- Current directory
- Home directory
- Folder of this script
- File next to this script, from anywhere
- Expand
~ - From a
file://URI (3.13+) - To a
file://URI (absolute paths) - Back to a string (or
os.fspath(p))
Most APIs (open, shutil, subprocess, pandas, polars) accept Path objects directly: no str() needed.
data.tar.gzdata.tar.gz[".tar", ".gz"]/srv/app/srv("/", "srv", "app", "data.tar.gz")/(drive + root,C:\on Windows)True
- Swap the extension
- Drop the extension
- Swap the file name
- Keep the extension, rename the stem
- Absolute, symlinks and
..resolved - Absolute, nothing resolved
- Strip a prefix (
ValueErrorif not under it) - Allow
../in the result (3.12+) - Is it inside that folder?
- Target of a symlink
- Forward slashes, even on Windows
- Anything there?
- Regular file
- Directory
- Symbolic link
- Broken symlinks count too
- Same file on disk
- Size in bytes
- Modified time (epoch seconds)
- Cached type check (3.14+, free after
iterdir) - Owner name (POSIX, also
group())
- Whole file as
str(UTF-8 by default in 3.15) - Strip a BOM (Excel exports)
- Whole file as
bytes - Create / overwrite, returns chars written
- Force Unix line endings
- Write bytes
- Append (any
open()mode) - Lines without
\n - Iterate lazily over a big file
- Create empty / update mtime
write_text() replaces the file in place. For a crash-safe write, write to p.with_suffix(".tmp") and tmp.replace(p).
- Create one level
- Like
mkdir -p - Mode for the created parents (3.15+)
- Direct children (any order)
- Sorted children
- Files only
- Remove an empty directory
- Remove a tree (no pathlib equivalent)
- Matches in this folder
- Recursive
- Same as
glob("**/*.py") - Directories only (trailing slash)
- Character class, any case
- Follow symlinked folders (3.13+)
- Like
os.walk, yieldsPaths (3.12+) - Prune folders while walking
- Match a whole path with
**(3.13+) - Match from the right
glob() returns a lazy generator in arbitrary order. Wrap it in sorted() for stable output.
Copy, move & delete v3.14+
- Copy a file or a whole tree, returns
dst - Copy into a folder, same name
- Keep times and permissions
- Copy links as links
- Move / rename, across filesystems too
- Move into a folder
- Rename (same filesystem only)
- Rename, overwrite
dst(atomic) - Delete a file, no error if missing
- Make
pa symlink totarget - Make
pa hard link
- Import
- Unix path on any OS
C:\Users\ada, on any OSC:/a/b- Split URL-like keys
Pure paths never touch the disk, so they are safe for paths that belong to another machine (S3 keys, remote hosts).
- Path(a) / "b"
- p.name
- p.parent
- p.suffix
- p.absolute()
- p.resolve()
- p.exists()
- p.stat().st_size
- p.mkdir(parents=True, exist_ok=True)
- p.iterdir()
- Path().glob("**/*.py")
- p.unlink()
- Path(a).copy(b)
- Path(a).move(b)
- p.read_text()
