Organizing Files & Folders Using Python Part-1

๐Ÿ“‚ Organizing Files & Folders Using Python (Path & OS) — Part 1

Managing files and folders is a core skill for every developer and power user.


๐Ÿ“Œ Table of Contents (jump links)


๐Ÿ“ Understanding File Paths in Python

Paths are strings that indicate where a file or folder lives:

  • Windows: C:\Users\Admin\data\file.txt
  • Linux/macOS: /home/user/data/file.txt

Python libraries:

  • ๐Ÿ“ฆ os — long-standing, very flexible (functions like os.path.join, os.listdir, os.walk).
  • ๐Ÿงญ pathlib.Path — object-oriented paths (recommended for readability and fewer bugs).

Example tree (visualized):

๐Ÿ“ project/
 ├── ๐Ÿ“ data/
 │    ├── ๐Ÿ“ reports/
 │    │    ├── ๐Ÿ“„ summary.txt
 │    │    ├── ๐Ÿ“„ sales.csv
 │    └── ๐Ÿ“ images/
 │         ├── ๐Ÿ–ผ️ logo.png
 └── ๐Ÿ“ scripts/
      └── ๐Ÿ“„ organizer.py

๐Ÿ“ Creating Files & Folders at a Specific Path

๐Ÿงฑ Using os.makedirs (create nested folders)


import os

path = "project/data/reports"

# create nested folders safely (no error if they already exist)
os.makedirs(path, exist_ok=True)

print("๐Ÿ“ Created:", path)

Resulting structure:


๐Ÿ“ project/
 └── ๐Ÿ“ data/
     └── ๐Ÿ“ reports/

✅ Checking Path Availability

๐Ÿ” Path.exists()


from pathlib import Path

p = Path("project/data/reports")

print("Exists?", p.exists()) # Output will be True or False

๐Ÿ“„ Checking Whether Path is File or Folder


import os
from pathlib import Path

p1 = "project/data/reports/summary.txt"
p2 = "project/data/reports"

pp1 = Path(p1)
pp2 = Path(p2)
print("Path - is_file:", pp1.is_file())
print("Path - is_dir:", pp2.is_dir())

Output example:


๐Ÿ“„ Path - is_file: True
๐Ÿ“ Path - is_dir: True

๐Ÿ“‚ Fetching Files & Folders Inside a Directory

๐Ÿงฉ Using pathlib.Path.iterdir() (Path objects)


from pathlib import Path

folder = Path("project/data")

for item in folder.iterdir(): # folder.iterdir() is a list of all files and folders inside the parent folder
    if item.is_file():
        print("๐Ÿ“„", item.name)
    else:
        print("๐Ÿ“", item.name)

Example output:


๐Ÿ“ reports
๐Ÿ“ images

๐Ÿ” Filtering Files by Extension & Other Criteria

✅ Filter by extension (case-insensitive)


from pathlib import Path

folder = Path("project/data/reports")
ext = ".txt"

for f in folder.iterdir():
    if f.is_file() and f.suffix.lower() == ext:
        print("๐Ÿ“„", f.name)

Example output:


๐Ÿ“„ summary.txt

๐Ÿงพ Filter by multiple extensions


from pathlib import Path

exts = {".jpg", ".jpeg", ".png", ".gif"}
for p in Path("project/data/images").iterdir():
    if p.is_file() and p.suffix.lower() in exts:
        print("๐Ÿ–ผ️", p.name)

Previous Post Next Post

Contact Form