Pathlib Module in Python

Getting your Trinity Audio player ready...

Working with files and folders is one of the most common tasks in programming — and Python makes it incredibly easy with the Pathlib module.

If you’ve ever struggled with os.path.join() or os.path.exists(), then you’ll love Pathlib — it’s modern, object-oriented, and far more readable!

Pathlib Module in Python

What is Pathlib?

The Pathlib module (introduced in Python 3.4) provides a high-level, object-oriented way to handle file system paths.
It replaces many old-style os and os.path functions, making code more clean, readable, and cross-platform.

You can think of Pathlib as a smart file manager for your code.


Importing Pathlib Module

from pathlib import Path

That’s it!
Now you can start working with files and directories using Path objects.


Creating Path Objects

from pathlib import Path

# Current directory
current = Path()

# Specific folder
downloads = Path("C:/Users/Tejas/Downloads")

# Relative path
data_folder = Path("data/files")

Each path here is an object — meaning you can call methods and access properties directly on it.


Useful Path Attributes

AttributeDescriptionExample
.nameFile or folder namePath("data/report.csv").name → 'report.csv'
.stemFile name without extension'report'
.suffixFile extension'.csv'
.parentParent directory'data'
.exists()Check if path existsTrue/False
.is_file()Check if path is a fileTrue/False
.is_dir()Check if path is a directoryTrue/False

Joining and Navigating Paths

Forget os.path.join() — Pathlib makes this easier with the / operator!

from pathlib import Path

base = Path("C:/Users/Tejas/Documents")
file = base / "projects" / "python" / "notes.txt"

print(file)
# Output: C:\Users\Tejas\Documents\projects\python\notes.txt

Cool, right? The / operator automatically joins paths correctly for Windows, Mac, and Linux.

Also Read: OS Module in Python


Listing Files and Folders

path = Path("C:/Users/Tejas/Downloads")

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

You can also filter files:

for file in path.glob("*.pdf"):
    print(file)

Use rglob() to search recursively in subfolders:

for file in path.rglob("*.xlsx"):
    print(file)

Reading and Writing Files

Pathlib makes file I/O super simple.

Write text to a file

file = Path("notes.txt")
file.write_text("Python is awesome!")

Read text from a file

content = file.read_text()
print(content)

Binary files

binary_data = Path("image.png").read_bytes()

Creating and Deleting Files or Folders

# Create a new folder
Path("backup").mkdir(exist_ok=True)

# Create nested folders
Path("data/2025/reports").mkdir(parents=True, exist_ok=True)

# Delete a file
Path("notes.txt").unlink()

# Remove an empty directory
Path("backup").rmdir()

⚠️ Note: .rmdir() only removes empty folders.


Rename or Move Files

old = Path("old_report.txt")
new = Path("archive/report_2025.txt")

old.rename(new)

Example – File Organizer Using Pathlib

Let’s create a File Organizer Script that automatically moves files into folders based on their extensions.

Project Description

You have a messy Downloads folder — PDFs, images, Excel files, and ZIPs everywhere.
Let’s organize them automatically using Pathlib!


Full Code

from pathlib import Path
import shutil

def organize_files(folder_path):
    path = Path(folder_path)

    for file in path.iterdir():
        if file.is_file():
            ext = file.suffix.lower()

            if ext in [".jpg", ".png", ".jpeg"]:
                target = path / "Images"
            elif ext in [".pdf"]:
                target = path / "PDFs"
            elif ext in [".xlsx", ".csv"]:
                target = path / "Spreadsheets"
            elif ext in [".zip", ".rar"]:
                target = path / "Archives"
            else:
                target = path / "Others"

            target.mkdir(exist_ok=True)
            shutil.move(str(file), str(target / file.name))
            print(f"Moved: {file.name}{target}")

folder = input("Enter folder path to organize: ")
organize_files(folder)

How It Works

  1. Iterate through all files using Path.iterdir().
  2. Check file extensions using .suffix.
  3. Create target folders (Images, PDFs, etc.) dynamically.
  4. Move files using shutil.move().
  5. Print progress as files are moved.

Advantages of Pathlib

✅ Cross-platform compatibility
✅ Cleaner and more readable syntax
✅ Integrated file handling (read/write)
✅ Easy navigation and pattern matching


Bonus: Common Pathlib + Shutil Combo

TaskCode
Copy a fileshutil.copy(src, dst)
Move a fileshutil.move(src, dst)
Delete foldershutil.rmtree(folder_path)
Get file sizefile.stat().st_size

Final Thoughts

The Pathlib module is a must-learn for every Python developer.
It simplifies file operations, improves code readability, and reduces errors.

By mastering Pathlib, you’ll make your scripts cleaner, safer, and more powerful — especially when automating file tasks or building real-world tools.

What’s Next?

In the next post, we’ll learn about the Regular Expressions in Python

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Translate »
Scroll to Top