๐Ÿ Python Examples - Comprehensive Code Library
โ† Back to PranavKulkarni.org
Lesson 1 ยท Automation

File System Operations & Management

Automate file moving, renaming, and organization using os and pathlib.

os vs. pathlib

While os is the classic way to handle paths, pathlib provides a modern, object-oriented approach.

Pathlib Basics

from pathlib import Path

# Current directory
cwd = Path.cwd()

# Joining paths
target = cwd / "backups" / "data.txt"

# Checking existence
if target.exists():
    print("Found it!")

Common Operations

# Create directory
Path("new_folder").mkdir(parents=True, exist_ok=True)

# Iterate over files
for file in Path(".").glob("*.py"):
    print(file.name)

# Move/Rename
file.rename("renamed_" + file.name)

High-Level Operations (shutil)

For operations like copying and archiving entire trees, use shutil.

import shutil

# Copy a directory
shutil.copytree("source", "dest")

# Create a zip archive
shutil.make_archive("backup", 'zip', "data/")

โœ… Practice (20 minutes)

  • Write a script that finds all .jpg files in a folder and moves them to an images subfolder.
  • Modify the script to add a timestamp prefix to each moved file.
  • Create a daily backup script that zips your project folder.