๐ 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
- ๐ Creating Files & Folders at a Specific Path
- ✅ Checking Path Availability
- ๐ Checking Whether Path is File or Folder
- ๐ Fetching Files & Folders Inside a Directory (iter & os.listdir)
- ๐ Filtering Files by Extension & Other Criteria
๐ 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 likeos.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)