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:
✨ Recommended for modern Python file handling
/ operator to join paths cleanly.exists(), is_file(), is_dir(), glob(), read_text(), write_text(), etc.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.This example shows how to create Path objects and inspect them.
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)
With pathlib, you can read and write text files using simple methods like write_text() and read_text().
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)
You can iterate over directory contents and filter files by patterns using iterdir(), glob(), and rglob().
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)
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)./ 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.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.pathlib over os.path in new Python code for better readability and maintainability./ operator for joining paths instead of string concatenation.exists(), is_file(), or is_dir() before operating on paths to avoid errors.mkdir(parents=True, exist_ok=True) to safely create nested directories.open() with Path objects for more control, instead of read_text().Path.cwd() and Path.home().demo_pathlib in the current directory.info.txt and writes some text using write_text().rglob("*.py") to list all Python files in your project folder and prints their sizes using path.stat().st_size..log files in a folder.unlink() if confirmed.