← Back to Python Course | Chapter 12: Standard Library | Lesson 7 of 9

Python pathlib Module

pathlib treats file locations as friendly objects, like a map you can read and follow easily. It works the same on different computers.
Syntax
python
from pathlib import Path

path = Path("folder/file_name")
path.exists()
path.read_text()

What is pathlib?

pathlib represents filesystem paths as objects rather than plain strings, giving you methods and operators (like / for joining) instead of manual string concatenation.

This object-oriented approach reduces the cross-platform bugs that come from hand-building paths with hardcoded slashes.

Example: What is pathlib?

python
from pathlib import Path
p = Path("folder") / "file.txt"  # / joins path segments
print(p)

Extracting Path Properties

A Path object exposes ready-made properties for common path pieces: .parent for the containing directory, .name for the final filename component, and .suffix for the file extension.

Pulling these out manually from a raw string would otherwise mean writing fragile string-splitting logic.

Example: Extracting Path Properties

python
from pathlib import Path
p = Path("/home/user/notes.txt")
print(p.parent)  # containing directory
print(p.name)  # final filename component
print(p.suffix)  # file extension

Checking File Existence

Path.exists() checks whether the path actually points to something on disk before you attempt to open or read it, letting you fail gracefully with a clear message instead of hitting an unhandled FileNotFoundError deep inside your program's logic.

Example: Checking File Existence

python
from pathlib import Path
p = Path(".")
print(p.exists())  # checks the path is actually on disk before using it

Reading and Writing Files

Path.read_text() and Path.write_text() (plus their _bytes counterparts) read or write a file's entire contents in a single call, without the boilerplate of manually opening a file handle, reading it, and remembering to close it afterward.

Example: Reading and Writing Files

python
from pathlib import Path
p = Path("notes.txt")
p.write_text("hello")  # writes without manually opening/closing a file
print(p.read_text())  # reads the whole file in one call

Working with Directories

Path.mkdir() creates new directories (with a parents=True option to create intermediate ones as needed), and Path.iterdir() lets you loop over everything directly inside a directory, giving you Path objects back rather than plain filename strings.

Example: Working with Directories

python
from pathlib import Path
p = Path("demo_dir")
p.mkdir(exist_ok=True)  # creates the directory, no error if it already exists
print(list(Path(".").iterdir())[:1])  # lists entries as Path objects
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Adding paths with +, when Path("a") / "b" is the correct way to join them.
  2. Forgetting that a Path is not a string, so functions that need text may require str(path).
  3. Calling read_text() on a missing file, which raises FileNotFoundError; check path.exists() first.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.