Python Pathlib Tutorial: Modern File and Directory Handling with Examples

26 Jan 2026

The Python pathlib module is a modern way to work with files and directories. It provides a clean, object-oriented approach to file system paths and is recommended over the traditional os module for most new Python projects.

If you want cleaner code, better readability, and cross-platform compatibility, pathlib is the right choice.


What Is Pathlib in Python?

pathlib is a built-in Python module that represents file system paths as objects instead of strings.

This means you can:

  • Work with files and folders easily
  • Avoid OS-specific path issues
  • Write cleaner and more readable code

πŸ“Œ Introduced in Python 3.4+.


How to Import Pathlib

from pathlib import Path

Create a Path Object

path = Path("data.txt")
print(path)

You can also create folder paths:

Path("projects/python/app")

Get Current Working Directory

Path.cwd()

πŸ“Œ Real-world use:

Used in automation scripts and CLI tools.

Create Files and Directories

Create a Directory

Path("my_folder").mkdir()

Create nested directories:

Path("projects/python/app").mkdir(parents=True, exist_ok=True)

Create an Empty File

Path("sample.txt").touch()

Check File or Directory Existence

path = Path("sample.txt")

path.exists()
path.is_file()
path.is_dir()

πŸ“Œ Prevents runtime errors.


Read and Write Files (Cleaner Than os)

Write to a File

path = Path("note.txt")
path.write_text("Hello, Pathlib!")

Read from a File

path.read_text()

Path Operations (Very Important)

Join Paths (No os.path.join Needed)

folder = Path("data")
file = folder / "info.txt"

πŸ“Œ / operator automatically handles OS paths.


Get File Name, Extension, Parent

path = Path("images/photo.png")

path.name        # photo.png
path.stem        # photo
path.suffix      # .png
path.parent

Rename, Move, and Delete Files

Rename File

path.rename("new_name.txt")

Delete File

path.unlink()

Delete Empty Folder

Path("my_folder").rmdir()

List Files and Directories

List All Files

Path(".").iterdir()

List Only Specific File Types

for file in Path(".").glob("*.txt"):
    print(file)

Recursive Search

Path(".").rglob("*.py")

πŸ“Œ Real-world use:

Search tools, code scanners, backup utilities.

Environment-Aware Paths

Home Directory

Path.home()

User Desktop (Cross-Platform)

Path.home() / "Desktop"

Real-World Pathlib Examples

Delete All .log Files

for file in Path(".").glob("*.log"):
    file.unlink()

Create Daily Backup Folder

from datetime import date
from pathlib import Path

folder = Path(str(date.today()))
folder.mkdir(exist_ok=True)


Final Thoughts

The Python pathlib module is the future of file and directory handling in Python. It makes your code cleaner, safer, and more readable, while working smoothly across all operating systems.

If you’re starting a new Python project πŸ‘‰ choose pathlib first πŸš€