Python pathlib Cheatsheet

1. Importing
from pathlib import Path
2. Creating Paths
# Current working directory
p = Path.cwd()

# Home directory
home = Path.home()

# Relative path
p = Path("folder/subfolder/file.txt")

# Absolute path
p = Path("/usr/local/bin")

# Convert to string
str_path = str(p)
3. Path Components
p = Path("/home/max/docs/report.pdf")

p.name       # "report.pdf"
p.stem       # "report"
p.suffix     # ".pdf"
p.suffixes   # [".tar", ".gz"]
p.parent     # "/home/max/docs"
p.parents[0] # "/home/max/docs"
p.parents[1] # "/home/max"
4. Path Operations
# Joining paths
p = Path("/home/max") / "docs" / "report.pdf"

# Replace filename or extension
p.with_name("new_file.txt")
p.with_suffix(".md")
5. File / Directory Checks
p.exists()     # True/False
p.is_file()    # True if file
p.is_dir()     # True if directory
p.is_symlink() # True if symlink
6. File System Operations
# Read / write text
p.write_text("Hello World")
content = p.read_text()

# Read / write bytes
p.write_bytes(b"binary data")
data = p.read_bytes()

# Make directories
Path("new/folder").mkdir(parents=True, exist_ok=True)

# Remove file
p.unlink()

# Rename / move
p.rename("new_name.txt")
p.replace("some/other/location.txt")
7. Glob Patterns
# Match all .txt files
for file in Path("docs").glob("*.txt"):
    print(file)

# Recursive glob
for file in Path("docs").rglob("*.txt"):
    print(file)
8. Resolve & Absolute Paths
p = Path("docs/../report.pdf")
p.resolve()  # Absolute normalized path
9. Path.iterdir()
p = Path("docs")
for item in p.iterdir():
    print(item)

# Filter files only
for f in Path(".").iterdir():
    if f.is_file():
        print(f)

# Filter directories only
for d in Path(".").iterdir():
    if d.is_dir():
        print(d)

# Sorted
for entry in sorted(Path(".").iterdir()):
    print(entry.name)

# Filter by extension
for f in Path(".").iterdir():
    if f.suffix == ".txt":
        print(f)

# List comprehension
files = [f.name for f in Path(".").iterdir() if f.is_file()]
10. Quick Comparison
Method Scope Example
iterdir() Direct children only Path(".").iterdir()
glob("*.py") Pattern-matching, 1 level deep Path(".").glob("*.py")
rglob("*.py") Recursive search Path(".").rglob("*.py")
Pathlib Methods - Arguments Explained
Method Arguments Default Explanation
mkdir() mode, parents, exist_ok 0o777, False, False Create a directory. parents=True creates parent directories. exist_ok=True ignores if directory exists.
rmdir() - - Remove empty directory. Raises OSError if not empty.
unlink() missing_ok False Delete a file. missing_ok=True ignores if file missing.
rename() target - Rename or move file. Overwrites not allowed if exists.
replace() target - Rename or move file. Overwrites if target exists.
touch() mode, exist_ok 0o666, True Create empty file. exist_ok=True ignores if file exists.
open() mode, encoding "r", None Open file handle like open().
read_text() encoding, errors None, None Read file as string.
write_text() data, encoding, errors - Write string to file.
glob() pattern - Pattern match files in directory.
rglob() pattern - Recursive pattern match files.
iterdir() - - Iterate over directory entries (direct children only).