Python Automation Projects
# Python Automation Projects
Welcome to Chapter 27! Automation is Python's superpower. In this chapter, you'll build real projects that automate repetitive tasks — saving hours of manual work.
---
1. Learning Objectives
- Automate file and folder management.
- Send automated emails.
- Schedule tasks programmatically.
- Work with PDFs and Excel files.
- Build practical automation scripts.
---
2. Project 1: Automatic File Organizer
Organizes files in a folder by their extensions:
```python id="py27_project1" import os import shutil from pathlib import Path
def organize_files(directory): """Organize files into folders by extension""" extension_map = { "Images": [".jpg", ".jpeg", ".png", ".gif", ".svg", ".bmp", ".webp"], "Documents": [".pdf", ".doc", ".docx", ".txt", ".xlsx", ".csv", ".pptx"], "Videos": [".mp4", ".avi", ".mkv", ".mov", ".wmv"], "Audio": [".mp3", ".wav", ".flac", ".aac", ".ogg"], "Archives": [".zip", ".rar", ".7z", ".tar", ".gz"], "Code": [".py", ".js", ".html", ".css", ".java", ".cpp"], } dir_path = Path(directory) moved_count = 0 for file in dir_path.iterdir(): if file.is_file(): ext = file.suffix.lower() folder_name = "Others" for category, extensions in extension_map.items(): if ext in extensions: folder_name = category break target_dir = dir_path / folder_name target_dir.mkdir(exist_ok=True) shutil.move(str(file), str(target_dir / file.name)) moved_count += 1 print(f" 📁 {file.name} → {folder_name}/") print(f"\n ✅ Organized {moved_count} files!")
# Usage: organize_files("/path/to/messy/folder") print("=" * 40) print(" 📁 FILE ORGANIZER") print("=" * 40) folder = input(" Enter folder path: ") if os.path.isdir(folder): organize_files(folder) else: print(" ❌ Invalid directory!")
python id="py27_project2" import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart
def send_email(sender, password, recipient, subject, body): """Send an email using SMTP""" msg = MIMEMultipart() msg["From"] = sender msg["To"] = recipient msg["Subject"] = subject msg.attach(MIMEText(body, "html")) try: # Gmail SMTP server with smtplib.SMTP("smtp.gmail.com", 587) as server: server.starttls() # Enable encryption server.login(sender, password) server.send_message(msg) print(" ✅ Email sent successfully!") except Exception as e: print(f" ❌ Error: {e}")
# Usage (use App Password for Gmail, not regular password) # send_email( # "your_email@gmail.com", # "your_app_password", # "recipient@example.com", # "Hello from Python!", # "<h1>Automated Email</h1><p>Sent with Python!</p>" # )
python id="py27_project3" import os from pathlib import Path
def bulk_rename(directory, prefix="file", start=1): """Rename all files with a sequential prefix""" dir_path = Path(directory) files = sorted([f for f in dir_path.iterdir() if f.is_file()]) print(f"\n Renaming {len(files)} files...") for i, file in enumerate(files, start): new_name = f"{prefix}_{i:03d}{file.suffix}" new_path = dir_path / new_name file.rename(new_path) print(f" {file.name} → {new_name}") print(f"\n ✅ Renamed {len(files)} files!")
# Usage: bulk_rename("/path/to/photos", prefix="vacation", start=1)
python id="py27_project4" import os import platform import shutil from datetime import datetime
def system_report(): """Generate a system information report""" print("=" * 45) print(" 💻 SYSTEM MONITOR REPORT") print("=" * 45) # System info print(f"\n {'System':<15}: {platform.system()} {platform.release()}") print(f" {'Machine':<15}: {platform.machine()}") print(f" {'Processor':<15}: {platform.processor()[:30]}") print(f" {'Python':<15}: {platform.python_version()}") # Disk usage total, used, free = shutil.disk_usage("/") print(f"\n Disk Usage:") print(f" {'Total':<15}: {total // (230)} GB") print(f" {'Used':<15}: {used // (230)} GB") print(f" {'Free':<15}: {free // (2**30)} GB") print(f" {'Usage':<15}: {used/total*100:.1f}%") # Report time print(f"\n Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print("=" * 45)
system_report()
python id="py27_project5" import random import string
def generate_password(length=16, uppercase=True, digits=True, special=True): """Generate a secure random password""" chars = string.ascii_lowercase if uppercase: chars += string.ascii_uppercase if digits: chars += string.digits if special: chars += "!@#$%^&*" password = ''.join(random.choice(chars) for _ in range(length)) # Ensure at least one of each required type required = [random.choice(string.ascii_lowercase)] if uppercase: required.append(random.choice(string.ascii_uppercase)) if digits: required.append(random.choice(string.digits)) if special: required.append(random.choice("!@#$%^&*")) pwd_list = list(password[:length - len(required)] + ''.join(required)) random.shuffle(pwd_list) return ''.join(pwd_list)
print("=" * 40) print(" 🔐 PASSWORD GENERATOR") print("=" * 40)
for i in range(5): pwd = generate_password(16) print(f" {i+1}. {pwd}")
python id="py27_ex1" import time from datetime import datetime
def run_scheduler(task, interval_seconds, max_runs=5): """Simple task scheduler""" run = 0 while run < max_runs: run += 1 timestamp = datetime.now().strftime("%H:%M:%S") print(f" [{timestamp}] Run {run}: ", end="") task() time.sleep(interval_seconds)
# Example task def check_status(): print("System status: OK ✅")
# Run every 3 seconds, 5 times
# run_scheduler(check_status, 3, 5)
``
---
8. MCQs with Answers
Q1: shutil.move() does:
A) Copies file B) Moves file C) Deletes file D) Renames file
Answer: B
Q2: smtplib is for:
A) Reading email B) Sending email C) Building websites D) File management
Answer: B
Q3: Path.mkdir(exist_ok=True) does:
A) Always creates B) Creates if doesn't exist C) Deletes and creates D) Error
Answer: B
Q4: os.listdir() returns:
A) File sizes B) File names C) File paths D) File types
Answer: B
Q5: SMTP port for Gmail with TLS: A) 80 B) 443 C) 587 D) 25 Answer: C
Q6: pathlib.Path is:
A) Deprecated B) Modern path handling C) Only for Linux D) Only for Windows
Answer: B
Q7: shutil.disk_usage() returns:
A) CPU usage B) Disk total/used/free C) Memory usage D) Network usage
Answer: B
Q8: string.ascii_letters contains:
A) Digits B) Lowercase only C) Letters a-z + A-Z D) Special chars
Answer: C
Q9: time.sleep(5) pauses for:
A) 5 milliseconds B) 5 seconds C) 5 minutes D) 5 hours
Answer: B
Q10: Best way to iterate directory files: A) os.walk() B) glob.glob() C) Path.iterdir() D) All valid Answer: D
---
9. Interview Questions
- 1. Python automation use cases? File management, email, reports, data extraction, backups, testing.
-
2.
How to schedule Python scripts? schedule
library,cron(Linux), Task Scheduler (Windows),APScheduler.
- 3. How to send emails securely? Use App Passwords, environment variables for credentials, TLS encryption.
- 4. pathlib vs os.path? pathlib is modern, OOP, and more readable. os.path is older but still widely used.
- 5. How to handle file conflicts in automation? Check existence, use timestamps in names, or create numbered suffixes.
---
10. Summary
- Python excels at automating repetitive tasks.
-
Use pathlib
andshutilfor file management.
-
Use smtplib
for sending emails.
-
Use os
andplatform` for system information.
- Always handle errors and edge cases in automation scripts.
---
11. Next Chapter Recommendation
In Chapter 28: Data Analysis with Python Basics, you'll learn NumPy, Pandas, and data visualization! 🚀