PYTHON

Python Pathlib Module: Syntax, Usage, and Examples

The Python pathlib module provides a modern, object-oriented way to handle filesystem paths. It simplifies common file and directory operations using intuitive syntax and eliminates the need for scattered functions from the older os and os.path modules.

By using the module pathlib Python offers, you can write more readable and concise code when working with paths, files, directories, and file metadata.


What Is the Python Pathlib Module?

The Python pathlib module was introduced in Python 3.4 and is now the recommended way to work with filesystem paths. Instead of using strings to represent paths and relying on separate functions for file operations, pathlib treats paths as objects.

This module supports:

  • Platform-independent path handling
  • Reading, writing, and checking file existence
  • Creating and removing directories
  • Iterating through directory contents
  • Combining paths using operators

You can use it to handle both relative and absolute paths with ease.


How to Import the Pathlib Module in Python

To start using the pathlib module in Python, import the Path class:

from pathlib import Path

You can now create and manipulate paths using the Path object.

p = Path("example_folder")
print(p.exists())  # Checks if the path exists

This provides a much cleaner interface than string-based manipulation.


Creating Paths with the Path Class

You can create paths to files or directories using the Path class. This doesn't create the actual file or directory; it just represents the path.

from pathlib import Path

# Path to a file
file_path = Path("documents") / "report.txt"

# Path to a directory
dir_path = Path("/usr/local/bin")

The / operator works as a cleaner alternative to os.path.join().

You can also resolve the absolute path:

absolute = file_path.resolve()
print(absolute)

File and Directory Checks

The Python pathlib module provides built-in methods to check file types and properties:

path = Path("example.txt")

print(path.exists())      # True if the path exists
print(path.is_file())     # True if it's a file
print(path.is_dir())      # True if it's a directory
print(path.is_absolute()) # Checks if the path is absolute

This avoids the need for scattered os.path function calls and improves code clarity.


Reading and Writing Files with Pathlib

The module pathlib Python provides comes with read_text() and write_text() methods for basic file operations.

# Write to a file
path = Path("example.txt")
path.write_text("Hello from pathlib")

# Read from a file
content = path.read_text()
print(content)

You can also work with binary data:

binary_path = Path("image.png")
data = binary_path.read_bytes()
binary_path.write_bytes(data)

This streamlines reading and writing operations.


Creating and Deleting Directories

The pathlib module allows you to create and delete directories using intuitive syntax:

# Create a directory
Path("new_folder").mkdir()

# Create nested directories
Path("nested/folder/structure").mkdir(parents=True, exist_ok=True)

# Remove a file or directory
Path("example.txt").unlink()     # Delete file
Path("new_folder").rmdir()       # Delete empty folder

Use caution with unlink() and rmdir() as they do not prompt before deletion.


Listing Directory Contents

You can list the contents of a directory using .iterdir():

path = Path(".")

for item in path.iterdir():
    print(item)

Filter only files or directories:

files = [f for f in path.iterdir() if f.is_file()]
dirs = [d for d in path.iterdir() if d.is_dir()]

This gives you precise control over directory listings.


Globbing and Pattern Matching

To search for files using wildcards, use glob() or rglob():

# Match all .txt files in the current folder
for txt_file in Path(".").glob("*.txt"):
    print(txt_file)

# Match all .txt files recursively
for txt_file in Path(".").rglob("*.txt"):
    print(txt_file)

These methods are powerful tools for file searching.


Accessing File Metadata

Path objects can return metadata about files and directories:

path = Path("example.txt")

print(path.name)        # File name
print(path.stem)        # File name without extension
print(path.suffix)      # File extension
print(path.parent)      # Parent directory
print(path.stat())      # Full metadata (size, permissions, modified time)

You can use .stat() to check when the file was last modified:

import time

timestamp = path.stat().st_mtime
print(time.ctime(timestamp))

Renaming and Moving Files

You can rename or move files using the .rename() method:

old_path = Path("old_name.txt")
new_path = Path("new_name.txt")

old_path.rename(new_path)

To move a file into a different directory:

destination = Path("archive/new_name.txt")
old_path.rename(destination)

The rename() method acts as both a move and rename operation.


Platform Compatibility

The Python pathlib module automatically handles platform-specific details like:

  • Forward slashes vs. backslashes
  • Drive letters on Windows
  • Case sensitivity on different file systems

You don’t need to worry about writing separate code for Windows and Unix systems.

For example:

from pathlib import Path
path = Path("folder") / "file.txt"
print(path)

This prints a valid path regardless of the platform.


Converting Between Path and String

Path objects can be converted to strings when needed:

p = Path("example.txt")
path_str = str(p)
print(path_str)

You can also convert back:

new_path = Path(path_str)

Some libraries still require string paths, so conversions remain useful.


Combining with Other Python Modules

Many standard libraries like shutil, zipfile, and csv now support Path objects directly.

Example with shutil:

import shutil
from pathlib import Path

shutil.copy(Path("file.txt"), Path("backup/"))

You no longer need to convert paths to strings before passing them to other modules.


When Not to Use Pathlib

The module pathlib Python provides doesn’t yet support every possible use case. If you need to:

  • Manipulate environment variables
  • Use system-level file descriptors
  • Interact with very old libraries

You might still rely on os, os.path, or other modules. But for most tasks, especially path manipulations, pathlib is now the standard.


The Python pathlib module modernizes the way you work with filesystem paths. It replaces many older, error-prone methods with a cleaner, object-oriented interface. You can easily read and write files, iterate through directories, match patterns, access metadata, and build paths in a platform-independent way.

Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster