Python Pathlib
Modern File Paths & Filesystem Operations
Master Python's modern path handling: Path objects, reading and writing files, path manipulation, glob patterns, and cross-platform filesystem operations. 18 interactive lessons with runnable code β crafted by @PoeticGlenn.
What you will learn
Everything about Python's pathlib module β the object-oriented way to handle filesystem paths introduced in Python 3.4. Learn how to create Path objects, read and write files, manipulate paths with operators, search with glob patterns, inspect file metadata, and write cross-platform code that works on Windows, macOS, and Linux. Each concept is broken down step-by-step with interactive code examples from @PoeticGlenn.
Why Pathlib Replaces os.path
Before pathlib, Python developers relied on the os.path module β a collection of
string-based functions like os.path.join() and os.path.exists(). While functional,
this approach treats paths as plain strings, leading to verbose code and platform-specific bugs.
pathlib, introduced in Python 3.4, brings an object-oriented API that makes path handling
intuitive, readable, and cross-platform. This curriculum, designed by
@PoeticGlenn, teaches you everything you need to work with
files and directories using the modern Python way.
Object-Oriented
Paths are objects with methods and properties, not just strings. More discoverable, more powerful.
Cross-Platform
One API for Windows, macOS, and Linux. No more worrying about backslashes vs forward slashes.
More Concise
Use the / operator to join paths. Read files in one line. Replace verbose os.path calls.
"Files are the memory of a program. Pathlib gives you a clean, safe way to reach them." β @PoeticGlenn π
Every Python Program Touches Files
Whether you're building a data pipeline, a web app, or an automation script, you'll interact with files
and directories. pathlib gives you a clean, powerful API that handles the messy details
of filesystem operations for you. This curriculum, curated by @PoeticGlenn,
teaches you to write code that's readable, maintainable, and platform-agnostic.
π File I/O Made Simple
Read and write files with a single method call. No more context manager boilerplate for simple tasks.
π Powerful Search
Find files by extension, name pattern, or recursively with glob() and rglob().
π§© Composable Paths
Use the / operator to build paths. Chain methods to inspect, modify, and traverse.
π‘οΈ Safer Operations
Built-in methods for common tasks: exists(), is_file(), rename(), unlink().
The Modern Standard for File Paths
Since its introduction, pathlib has become the recommended way to handle paths in Python.
Major libraries like black, pytest, and django now use it
internally. The Python documentation itself recommends pathlib over os.path
for new code. This curriculum, designed by @PoeticGlenn,
gives you the skills that modern Python projects expect.
Pythonic Standard
Recommended by the Python docs and adopted by major libraries across the ecosystem.
Safer Code
Object-oriented design catches errors earlier and makes intent clearer than raw string operations.
Future-Proof
New Python features build on pathlib. Learning it now keeps your codebase modern for years.
"Every path you build is a bridge between your program and the real world."
π Table of Contents
Jump to any section β all entries are equal size
π Path Basics β Creating Path Objects
Learn how to create and work with Path objects β the foundation of pathlib.
π 1.1 Creating Path Objects
The Path class is the primary entry point. Create one with a string or from the current directory.
Step-by-step explanation:
- Step 1: Import the
Pathclass frompathlib. - Step 2: Create a
Pathobject withPath("data"). - Step 3: Use
Path.cwd()for the current working directory. - Step 4: Use
Path.home()for the user's home directory.
from pathlib import Path # Create a Path object from a string data_path = Path("data") print("data_path:", data_path) print("type:", type(data_path)) # Current working directory cwd = Path.cwd() print("\ncwd:", cwd) # Home directory home = Path.home() print("home:", home) # These are Path objects, not strings print("\nis Path?", isinstance(data_path, Path))
Path objects are immutable. Every operation returns a new Path rather than modifying the original.π 1.2 PurePath vs Path
PurePath handles string operations only (no I/O). Path adds filesystem access.
Step-by-step explanation:
- Step 1: Use
PurePathfor platform-independent path manipulation. - Step 2: Use
Pathwhen you need to touch the actual filesystem.
from pathlib import PurePath, Path # PurePath β string operations only, no filesystem pure = PurePath("docs", "reports", "2026.pdf") print("pure:", pure) print("name:", pure.name) print("suffix:", pure.suffix) # Path β has filesystem methods real = Path("data.txt") print("\nreal:", real) print("has exists method:", hasattr(real, "exists"))
PurePath when you only need string operations β it works even on platforms where the path isn't valid.π Path Manipulation β Joining & Slicing
Build, split, and modify paths with the / operator and built-in properties.
π 2.1 Joining Paths with /
The / operator is the pathlib equivalent of os.path.join() β but cleaner.
Step-by-step explanation:
- Step 1: Start with a base
Path. - Step 2: Use
/ "subdir"to append components. - Step 3: Chain multiple
/operators for deep paths.
from pathlib import Path base = Path("/home/user") # Join with the / operator docs = base / "documents" report = docs / "2026" / "report.pdf" print("report:", report) # Join with multiple parts at once config = base / "config" / "settings.json" print("config:", config) # Works with Path objects too sub = Path("projects") full = base / sub / "app.py" print("full:", full)
/ operator handles platform-specific separators automatically. On Windows it produces backslashes; on Unix, forward slashes.π 2.2 Path Properties β name, stem, suffix, parent
Extract components from a path without string splitting.
Step-by-step explanation:
- Step 1: Create a
Pathto a nested file. - Step 2: Access
.namefor the filename. - Step 3: Use
.stemfor the name without extension. - Step 4: Use
.suffixfor the extension,.parentfor the directory.
from pathlib import Path p = Path("/home/user/documents/report.tar.gz") print("full path: ", p) print("name: ", p.name) print("stem: ", p.stem) print("suffix: ", p.suffix) print("suffixes: ", p.suffixes) print("parent: ", p.parent) print("parents[0]:", p.parents[0]) print("parents[1]:", p.parents[1]) print("parts: ", p.parts)
.suffix only returns the last extension (.gz) while .suffixes returns all of them (['.tar', '.gz']).π 2.3 with_name(), with_suffix(), and with_stem()
Create modified copies of a path without touching the original.
Step-by-step explanation:
- Step 1: Start with a
Path. - Step 2: Call
with_name()to change the filename. - Step 3: Call
with_suffix()to change the extension.
from pathlib import Path original = Path("/home/user/report.txt") print("original: ", original) renamed = original.with_name("summary.txt") print("with_name: ", renamed) resuffixed = original.with_suffix(".md") print("with_suffix: ", resuffixed) restemmed = original.with_stem("draft") print("with_stem: ", restemmed) # Original is unchanged print("original again:", original)
with_* methods return a new Path. The original object is never modified.π File Operations β Read & Write
Read, write, and manage files with simple one-line methods.
π 3.1 Reading Files
Use read_text() and read_bytes() for one-liner file reads.
Step-by-step explanation:
- Step 1: Create a
Pathobject. - Step 2: Call
.write_text()to create a file (for this example). - Step 3: Call
.read_text()to read it back.
from pathlib import Path p = Path("greeting.txt") # Write the file first p.write_text("Hello, Poetic Bytes!", encoding="utf-8") # Read the entire file as a string content = p.read_text(encoding="utf-8") print("Content:", content) print("Length: ", len(content)) # Check file exists and size print("Exists:", p.exists()) print("Size: ", p.stat().st_size, "bytes")
read_text() reads the entire file into memory. For large files, use open() with iteration.π 3.2 Writing Files
write_text() creates or overwrites a file in one call.
Step-by-step explanation:
- Step 1: Create a
Path. - Step 2: Call
.write_text()with your content. - Step 3: Optionally pass
encodingfor text data.
from pathlib import Path p = Path("notes.txt") # Write text (overwrites existing content) chars_written = p.write_text("Line 1\nLine 2\nLine 3\n", encoding="utf-8") print(f"Wrote {chars_written} characters") # Read it back print("\nFile contents:") print(p.read_text(encoding="utf-8"))
write_text() returns the number of characters written, which can be useful for logging or verification.π 3.3 Appending to Files
Open with mode="a" to add content without overwriting.
Step-by-step explanation:
- Step 1: Use
p.open("a")as a context manager. - Step 2: Write additional lines.
- Step 3: Close happens automatically.
from pathlib import Path p = Path("log.txt") p.write_text("Initial entry\n") # Append without overwriting with p.open("a", encoding="utf-8") as f: f.write("Second entry\n") f.write("Third entry\n") print(p.read_text(encoding="utf-8"))
Path.open() is a drop-in replacement for the built-in open(), but returns a context manager that works with with statements.π Directory Operations β Create, Rename, Delete
Manage directories and files with clear, readable methods.
π 4.1 Creating Directories
Use mkdir() for one directory, mkdir(parents=True) for nested ones.
Step-by-step explanation:
- Step 1: Create a
Pathto your directory. - Step 2: Call
mkdir()for a single level. - Step 3: Use
parents=Trueto create intermediate directories. - Step 4: Use
exist_ok=Trueto skip errors if it already exists.
from pathlib import Path # Create a single directory Path("mydir").mkdir(exist_ok=True) print("Created mydir") # Create nested directories nested = Path("data") / "raw" / "2026" nested.mkdir(parents=True, exist_ok=True) print("Created", nested) print("exists:", nested.exists()) print("is_dir:", nested.is_dir())
parents=True is like mkdir -p on Unix β it creates all intermediate directories.π 4.2 Renaming and Moving
Use rename() to rename or move a file or directory.
Step-by-step explanation:
- Step 1: Create the source
Path. - Step 2: Call
.rename(target)with the new path. - Step 3: If target is in a different directory, this acts as a move.
from pathlib import Path src = Path("notes.txt") src.write_text("original content") dst = Path("renamed.txt") src.rename(dst) print("src exists:", src.exists()) print("dst exists:", dst.exists()) print("dst content:", dst.read_text())
π 4.3 Deleting Files and Empty Directories
Use unlink() for files and rmdir() for empty directories.
Step-by-step explanation:
- Step 1: Create a file to delete.
- Step 2: Call
.unlink()to remove it. - Step 3: Call
.rmdir()for empty directories.
from pathlib import Path # Delete a file f = Path("temp.txt") f.write_text("bye") print("before:", f.exists()) f.unlink() print("after: ", f.exists()) # Delete an empty directory d = Path("empty_dir") d.mkdir(exist_ok=True) print("dir before:", d.exists()) d.rmdir() print("dir after: ", d.exists())
rmdir() only works on empty directories. For non-empty ones, use shutil.rmtree().π Glob Patterns β Find Files by Name
Search for files matching a pattern with glob() and rglob().
π 5.1 glob() β Match in One Directory
Find files matching a pattern without descending into subdirectories.
Step-by-step explanation:
- Step 1: Create a directory with sample files.
- Step 2: Call
.glob("*.txt")to find text files. - Step 3: Iterate over the results.
from pathlib import Path # Create sample files base = Path("glob_test") base.mkdir(exist_ok=True) (base / "a.txt").write_text("A") (base / "b.txt").write_text("B") (base / "c.md").write_text("C") (base / "d.py").write_text("D") # Find all .txt files print("*.txt files:") for f in base.glob("*.txt"): print(" ", f.name) # Find all .py files print("*.py files:") for f in base.glob("*.py"): print(" ", f.name)
π 5.2 rglob() β Recursive Search
rglob() searches recursively through all subdirectories.
Step-by-step explanation:
- Step 1: Create a nested directory structure.
- Step 2: Call
.rglob("*.py")to find all Python files recursively.
from pathlib import Path root = Path("recursive_test") (root / "sub1").mkdir(parents=True, exist_ok=True) (root / "sub2" / "deep").mkdir(parents=True, exist_ok=True) (root / "main.py").write_text("main") (root / "sub1" / "helper.py").write_text("helper") (root / "sub2" / "deep" / "utils.py").write_text("utils") (root / "readme.md").write_text("readme") print("All .py files (recursive):") for f in root.rglob("*.py"): print(" ", f.relative_to(root))
rglob("*.py") is equivalent to glob("**/*.py", recursive=True).π 5.3 iterdir() β List Contents
Iterate over all entries in a directory (files and subdirectories).
Step-by-step explanation:
- Step 1: Create a
Pathto a directory. - Step 2: Call
.iterdir()for all entries. - Step 3: Filter by
.is_file()or.is_dir().
from pathlib import Path base = Path("iterdir_test") base.mkdir(exist_ok=True) (base / "file1.txt").write_text("x") (base / "file2.txt").write_text("y") (base / "folder").mkdir(exist_ok=True) print("All entries:") for entry in sorted(base.iterdir()): kind = "DIR " if entry.is_dir() else "FILE" print(f" {kind} {entry.name}")
βΉοΈ Path Info β Check Existence & Metadata
Inspect paths with predicates and stat information.
π 6.1 Predicates β exists(), is_file(), is_dir()
Check what a path points to without opening it.
Step-by-step explanation:
- Step 1: Create sample file and directory.
- Step 2: Use
.exists()to check existence. - Step 3: Use
.is_file()and.is_dir()to check type.
from pathlib import Path f = Path("info_test.txt") f.write_text("data") d = Path("info_dir") d.mkdir(exist_ok=True) print("File predicates:") print(" exists: ", f.exists()) print(" is_file:", f.is_file()) print(" is_dir: ", f.is_dir()) print("\nDir predicates:") print(" exists: ", d.exists()) print(" is_file:", d.is_file()) print(" is_dir: ", d.is_dir()) print("\nMissing predicates:") missing = Path("nope.txt") print(" exists: ", missing.exists())
π 6.2 stat() β File Metadata
Get size, modification time, and other metadata with stat().
Step-by-step explanation:
- Step 1: Create a file.
- Step 2: Call
.stat()to get anos.stat_resultobject. - Step 3: Access
.st_sizefor bytes,.st_mtimefor modification time.
from pathlib import Path from datetime import datetime p = Path("stat_test.txt") p.write_text("Hello, world!") s = p.stat() print("Size in bytes:", s.st_size) print("Modified at: ", datetime.fromtimestamp(s.st_mtime)) print("Is regular file:", p.is_file())
st_mtime is a Unix timestamp. Use datetime.fromtimestamp() to convert it to a readable date.π₯οΈ Cross-Platform β Windows, macOS, Linux
Write code that works the same on every operating system.
π 7.1 Why Pathlib Beats Strings
Platform-specific separators are handled for you.
Step-by-step explanation:
- Step 1: Compare string concatenation with pathlib.
- Step 2: Observe that pathlib produces the right separator automatically.
- Step 3: Use
.as_posix()to always get forward slashes for URLs or config files.
from pathlib import Path # The / operator adapts to the current OS p = Path("data") / "files" / "report.txt" print("Native path:", p) # as_posix() always returns forward slashes print("POSIX path: ", p.as_posix()) # resolve() makes it absolute print("Absolute: ", p.resolve().parent)
data\files\report.txt. On Linux/macOS, it's data/files/report.txt β same code!π 7.2 resolve() and absolute()
resolve() canonicalizes the path, resolving symlinks and .. segments.
Step-by-step explanation:
- Step 1: Create a relative
Path. - Step 2: Call
.resolve()to get the absolute, symlink-resolved path. - Step 3: Use
.is_absolute()to check.
from pathlib import Path rel = Path("subdir") / ".." / "file.txt" print("Relative: ", rel) print("Resolved: ", rel.resolve()) print("Absolute?:", rel.is_absolute()) abs_path = Path("/tmp/data.txt") print("\nAbs path: ", abs_path) print("Absolute?:", abs_path.is_absolute())
resolve() also resolves symlinks. If you don't want that, use os.path.abspath() instead.π 7.3 Reading and Writing with Context Managers
For fine-grained control, use Path.open() instead of the one-liners.
Step-by-step explanation:
- Step 1: Open with
p.open("w")for writing. - Step 2: Write lines one by one.
- Step 3: Read back with
p.open("r").
from pathlib import Path p = Path("stream_test.txt") with p.open("w", encoding="utf-8") as f: for i in range(3): f.write(f"Line {i+1}\n") with p.open("r", encoding="utf-8") as f: for line in f: print("Read:", line.rstrip())
β Frequently Asked Questions β Python Pathlib
Common questions about pathlib, answered.
What's the difference between Path and PurePath?
+PurePath only handles string operations and doesn't touch the filesystem. Path extends it with filesystem methods like exists(), read_text(), and mkdir(). Use PurePath when you want platform-independent path manipulation without I/O.
Why use pathlib instead of os.path?
+Pathlib is object-oriented, more concise, and recommended by the Python docs. The / operator replaces verbose os.path.join() calls, and paths have properties like .name instead of separate functions like os.path.basename().
Is pathlib faster than os.path?
+Performance is roughly equivalent. Pathlib sometimes has a slight overhead due to object creation, but the readability and correctness benefits far outweigh any micro-differences. For hot loops, use os.path; for everything else, pathlib.
How do I convert a Path back to a string?
+Use str(path) for the native string, or path.as_posix() for forward-slash format. Both produce a plain string you can pass to libraries that don't accept Path objects.
Can I use pathlib with glob patterns?
+Yes β path.glob("*.txt") searches one directory, and path.rglob("*.txt") searches recursively. Both return generators of Path objects.
How do I delete a directory with pathlib?
+path.rmdir() only deletes empty directories. For non-empty ones, use shutil.rmtree(path). Pathlib doesn't include a recursive delete method by design, since it's a destructive operation.
Does pathlib work on Windows?
+Yes. On Windows, pathlib uses WindowsPath which handles backslashes correctly. On Unix, it uses PosixPath. The same code works on both β only the string representation differs.
How do I check if a path is a file or directory?
+Use path.is_file() and path.is_dir(). Both return False for paths that don't exist. Use path.exists() first if you need to distinguish missing paths from wrong-type paths.
π You've Mastered Python Pathlib
From creating Path objects to writing cross-platform filesystem code, you now have
a complete understanding of Python's modern path handling. You can join paths with
the / operator, read and write files in one line, search with glob patterns,
and manage directories with confidence.
This curriculum, crafted by @PoeticGlenn,
replaces all the old os.path patterns you've learned with cleaner, safer,
more Pythonic alternatives. The skills you've gained will serve you in every project
that touches the filesystem.
"Every path you build is a bridge between your program and the real world. Walk it with confidence." β Glenn Junsay Pansensoy (@PoeticGlenn)