Lesson 25: File & Directory Automation in Python

๐ŸŽฏ Lesson Objective

To learn how to automate repetitive file and folder tasks โ€” such as creating, renaming, moving, and deleting files โ€” using Pythonโ€™s built-in modules.


๐Ÿงฉ 1. What Is File & Directory Automation?

File and directory automation means using Python scripts to automatically perform operations like:

  • Organizing files (e.g., move images to โ€œPicturesโ€)
  • Creating backups
  • Renaming multiple files at once
  • Deleting unwanted or duplicate files
  • Generating folders automatically

This helps save time and reduce manual effort.


๐Ÿง  2. Modules Used

ModulePurpose
osInteract with the operating system (create/delete directories, rename files, etc.)
shutilCopy, move, or delete entire files or directories
globFind files using wildcards (e.g., *.txt)
pathlibModern, object-oriented way to handle file paths

โš™๏ธ 3. Accessing Current Working Directory

import os

# Get the current working directory
current_dir = os.getcwd()
print("Current Directory:", current_dir)

Example Output:

Current Directory: C:\Users\Sameer\Documents

๐Ÿ“ 4. Creating and Removing Directories

import os

# Create a new folder
os.mkdir("MyFolder")

# Create nested folders
os.makedirs("Projects/Python/Automation")

# Remove a folder (only if empty)
os.rmdir("MyFolder")

# Remove nested folders
os.removedirs("Projects/Python/Automation")

โœ… Note: To delete folders that contain files, use shutil.rmtree().


๐Ÿ“„ 5. Listing Files and Folders

import os

items = os.listdir(".")  # "." means current directory
print("Files and folders:", items)

Example Output:

Files and folders: ['main.py', 'data.txt', 'images', 'notes.docx']

๐Ÿชถ 6. Renaming Files and Folders

import os

# Rename a file
os.rename("old_name.txt", "new_name.txt")

# Rename a folder
os.rename("OldFolder", "NewFolder")

๐Ÿ“ฆ 7. Moving and Copying Files

Using the shutil module:

import shutil

# Copy a file
shutil.copy("data.txt", "backup/data_backup.txt")

# Move a file
shutil.move("notes.txt", "Documents/notes.txt")

# Delete a file
os.remove("temp.txt")

๐Ÿ” 8. Searching Files with glob

import glob

# Find all text files
text_files = glob.glob("*.txt")
print(text_files)

Output:

['data.txt', 'notes.txt', 'summary.txt']

You can also search recursively:

files = glob.glob("**/*.py", recursive=True)
print(files)

๐Ÿงฐ 9. Using pathlib for Modern Path Handling

from pathlib import Path

# Create a Path object
path = Path("example.txt")

# Check existence
if path.exists():
    print("File exists!")

# Get file details
print("File name:", path.name)
print("Extension:", path.suffix)
print("Parent directory:", path.parent)

๐Ÿ” 10. Example 1 โ€” Auto File Organizer

Automatically move files into folders based on their types.

import os
import shutil

source = "Downloads"
dest = "Organized"

# Create destination folder
os.makedirs(dest, exist_ok=True)

for file in os.listdir(source):
    filepath = os.path.join(source, file)

    if os.path.isfile(filepath):
        if file.endswith(('.jpg', '.png')):
            folder = "Images"
        elif file.endswith(('.pdf', '.docx')):
            folder = "Documents"
        elif file.endswith(('.mp3', '.wav')):
            folder = "Audio"
        else:
            folder = "Others"

        dest_path = os.path.join(dest, folder)
        os.makedirs(dest_path, exist_ok=True)
        shutil.move(filepath, dest_path)
        print(f"Moved {file} โ†’ {folder}")

โœ… Result:
Your โ€œDownloadsโ€ folder gets automatically sorted into Images, Documents, Audio, and Others folders.


๐Ÿงน 11. Example 2 โ€” Auto File Renamer

Rename all .txt files to have a numbered sequence.

import os

folder = "Reports"
files = os.listdir(folder)

count = 1
for file in files:
    if file.endswith(".txt"):
        old = os.path.join(folder, file)
        new = os.path.join(folder, f"report_{count}.txt")
        os.rename(old, new)
        count += 1

โœ… Result:
Files like data1.txt, summary.txt โ†’ become โ†’ report_1.txt, report_2.txt.


๐Ÿ—‘๏ธ 12. Example 3 โ€” Delete Old Files Automatically

Delete files older than 7 days.

import os, time

folder = "Logs"
now = time.time()

for file in os.listdir(folder):
    filepath = os.path.join(folder, file)
    if os.path.isfile(filepath):
        # Check age in seconds
        age = now - os.path.getmtime(filepath)
        if age > 7 * 24 * 60 * 60:
            os.remove(filepath)
            print(f"Deleted old file: {file}")

๐Ÿงฎ 13. Example 4 โ€” Backup Files Automatically

import shutil
import datetime

today = datetime.date.today()
backup_folder = f"Backup_{today}"

shutil.copytree("ProjectData", backup_folder)
print(f"Backup created: {backup_folder}")

โœ… Result:
Creates a folder like Backup_2025-10-25 containing a full copy of ProjectData.


๐Ÿ’ก 14. Example 5 โ€” Directory Tree Printer

from pathlib import Path

def print_tree(path, level=0):
    for item in path.iterdir():
        print(" " * level * 2 + "|--", item.name)
        if item.is_dir():
            print_tree(item, level + 1)

print_tree(Path("."))

Output Example:

|-- Documents
  |-- notes.txt
  |-- images
    |-- photo1.jpg
|-- main.py
|-- data.csv


Comments

Leave a Reply

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