๐ฏ 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
| Module | Purpose |
|---|---|
os | Interact with the operating system (create/delete directories, rename files, etc.) |
shutil | Copy, move, or delete entire files or directories |
glob | Find files using wildcards (e.g., *.txt) |
pathlib | Modern, 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

Leave a Reply