← Back to Chapters

Python Pathlib Module

?️ Python Pathlib Module

? Quick Overview

The pathlib module in Python provides an object-oriented way to work with file system paths. Instead of manually joining strings and using os.path, you work with Path objects that make your code more readable, safer, and cross-platform.

It supports operations like:

  • Creating path objects for files and directories.
  • Checking if paths exist and whether they are files or directories.
  • Reading from and writing to files using simple methods.
  • Navigating, joining and iterating over directory contents.

✨ Recommended for modern Python file handling

? Key Concepts

  • Path class – Represents filesystem paths in an OS-independent way.
  • PurePath classes – Represent paths without actually touching the filesystem.
  • Operator overloading – Use the / operator to join paths cleanly.
  • High-level methodsexists(), is_file(), is_dir(), glob(), read_text(), write_text(), etc.
  • Automatic handling of separators – Works on Windows, Linux, macOS without changes.

? Syntax and Core Ideas

Importing Path from pathlib:

from pathlib import Path

Creating Path objects:

  • Path("file.txt") – Relative path.
  • Path("/usr/bin") – Absolute path (POSIX style).
  • Path.home() – Current user home directory.
  • Path.cwd() – Current working directory.

Joining paths using / operator:

Path("folder") / "subfolder" / "file.txt"

Common methods:

  • p.exists() – Check if path exists.
  • p.is_file(), p.is_dir() – Check type.
  • p.mkdir(), p.unlink() – Create folder, delete file.
  • p.read_text(), p.write_text() – Simple text file I/O.
  • p.glob("*.py"), p.rglob("*.txt") – Pattern-based search.

? Basic Usage Example

This example shows how to create Path objects and inspect them.

? View Code Example
from pathlib import Path

# Current working directory
current_dir = Path.cwd()
print("Current directory:", current_dir)

# Home directory
home_dir = Path.home()
print("Home directory:", home_dir)

# Create a path to a file inside a folder
project_dir = current_dir / "project"
config_file = project_dir / "config.json"

print("Project directory path:", project_dir)
print("Config file path:", config_file)

? Reading and Writing Files

With pathlib, you can read and write text files using simple methods like write_text() and read_text().

? View Code Example
from pathlib import Path

# Create a Path object for a text file in the current directory
file_path = Path("notes.txt")

# Write text to the file (creates it if it does not exist)
file_path.write_text("Hello from pathlib! \nThis is a test file.")

# Read the text back
content = file_path.read_text()
print("File content:")
print(content)

? Working with Directories

You can iterate over directory contents and filter files by patterns using iterdir(), glob(), and rglob().

? View Code Example
from pathlib import Path

# Directory to inspect
directory = Path.cwd()

print("All items in directory:")
for item in directory.iterdir():
    print("-", item)

print("\nOnly Python files (*.py) using glob:")
for py_file in directory.glob("*.py"):
    print("-", py_file)

print("\nAll .txt files in this folder and subfolders using rglob:")
for txt_file in directory.rglob("*.txt"):
    print("-", txt_file)

? Live Output / Explanation

When you run the basic usage example:

  • Path.cwd() prints the folder from which your script is executed.
  • Path.home() prints your OS user home directory (for example, C:\Users\name on Windows or /home/name on Linux).
  • The / operator builds nested paths like project/config.json in a platform-independent way.

In the file I/O example:

  • write_text() creates the file if it does not exist and overwrites its content.
  • read_text() returns the entire file content as a single string.
  • You do not need to manually open or close the file – pathlib handles that internally.

In the directory example:

  • iterdir() returns all items (files and folders) directly inside the directory.
  • glob("*.py") lists all Python files only in that directory.
  • rglob("*.txt") searches recursively in all subdirectories.

? Common Use Cases

  • Building file paths for configuration files, logs, and data files.
  • Writing cross-platform code that runs on Windows, Linux, and macOS without changing separators.
  • Quickly reading and writing small text files.
  • Searching for specific file types in large directory trees.
  • Cleaning up temporary files and folders.

? Tips and Best Practices

  • Prefer pathlib over os.path in new Python code for better readability and maintainability.
  • Use the / operator for joining paths instead of string concatenation.
  • Always check with exists(), is_file(), or is_dir() before operating on paths to avoid errors.
  • Use mkdir(parents=True, exist_ok=True) to safely create nested directories.
  • When reading large files, consider using open() with Path objects for more control, instead of read_text().

? Try It Yourself

  1. Create a script that:
    • Prints your current working directory and home directory using Path.cwd() and Path.home().
    • Creates a folder called demo_pathlib in the current directory.
    • Inside it, creates a file info.txt and writes some text using write_text().
  2. Write a script that uses rglob("*.py") to list all Python files in your project folder and prints their sizes using path.stat().st_size.
  3. Build a small "cleanup" script that:
    • Searches for all .log files in a folder.
    • Asks the user for confirmation.
    • Deletes them using unlink() if confirmed.