Skip to content

pathlib

The Python pathlib module provides an object-oriented approach to handling file system paths. It offers classes to handle different types of paths, such as POSIX and Windows, making path manipulations more intuitive and less error-prone.

Here’s a quick example:

Language: Python
>>> from pathlib import Path
>>> bin = Path("/usr/bin")
>>> bin.exists()
True

Key Features

  • Provides classes for file system path manipulation
  • Supports both POSIX and Windows paths
  • Offers tools for common path operations like reading, writing, and iterating through files
  • Supports high-level file operations like copying and moving with Path.copy() and Path.move() (Python 3.14+)

Frequently Used Classes and Functions

Object Type Description
pathlib.Path Class Represents a file system path
pathlib.PurePath Class Provides path-handling operations that don’t access the file system
pathlib.Path.glob() Method Finds all matching pathnames
pathlib.Path.mkdir() Method Creates a new directory

Examples

Creating a directory:

Language: Python
>>> dir = Path("new_folder")
>>> dir.mkdir()
>>> dir.exists()
True

Writing and reading a file:

Language: Python
>>> file = Path("example.txt")
>>> file.write_text("Hello, World!")
13
>>> file.read_text()
'Hello, World!'

Iterating over files in a directory:

Language: Python
>>> for file in Path(".").iterdir():
...     print(file)
...

Common Use Cases

  • Facilitating cross-platform path manipulations
  • Navigating and manipulating file system paths
  • Reading and writing to files in a path-oriented manner

Real-World Example

Say you want to list all Python files in a directory and its subdirectories:

Language: Python
>>> from pathlib import Path
>>> project_dir = Path("project")
>>> python_files = list(project_dir.rglob("*.py"))
>>> python_files
[PosixPath('project/main.py'), PosixPath('project/utils/helper.py')]

In this example, you use pathlib to recursively find all Python files in a given directory.

Python 3 "pathlib" Module: Taming The Filesystem

Tutorial

Python's pathlib Module: Taming the File System

Handle file and folder paths the modern way with Python pathlib, a built-in module whose semantics work the same on every OS.

intermediate python stdlib

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Oct. 10, 2026