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="py27project1" import os import shutil from pathlib import Path
def organizefiles(directory): """Organize files into folders by extension""" extensionmap = { "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"], } dirpath = Path(directory) movedcount = 0 for file in dirpath.iterdir(): if file.isfile(): ext = file.suffix.lower() foldername = "Others" for category, extensions in extensionmap.items(): if ext in extensions: foldername = category break targetdir = dirpath / foldername targetdir.mkdir(existok=True) shutil.move(str(file), str(targetdir / file.name)) movedcount += 1 print(f" 📁 {file.name} → {foldername}/") print(f"\n ✅ Organized {movedcount} files!")
# Usage: organizefiles("/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="py27project2" import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart
def sendemail(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.sendmessage(msg) print(" ✅ Email sent successfully!") except Exception as e: print(f" ❌ Error: {e}")
# Usage (use App Password for Gmail, not regular password) # sendemail( # "youremail@gmail.com", # "yourapp_password", # "recipient@example.com", # "Hello from Python!", # "<h1>Automated Email</h1><p>Sent with Python!</p>" # )
python id="py27project3" import os from pathlib import Path
def bulkrename(directory, prefix="file", start=1): """Rename all files with a sequential prefix""" dirpath = Path(directory) files = sorted([f for f in dirpath.iterdir() if f.isfile()]) print(f"\n Renaming {len(files)} files...") for i, file in enumerate(files, start): newname = f"{prefix}{i:03d}{file.suffix}" newpath = dirpath / newname file.rename(newpath) print(f" {file.name} → {newname}") print(f"\n ✅ Renamed {len(files)} files!")
# Usage: bulk_rename("/path/to/photos", prefix="vacation", start=1)
python id="py27project4" import os import platform import shutil from datetime import datetime
def systemreport(): """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.pythonversion()}") # Disk usage total, used, free = shutil.diskusage("/") 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="py27project5" import random import string
def generatepassword(length=16, uppercase=True, digits=True, special=True): """Generate a secure random password""" chars = string.asciilowercase if uppercase: chars += string.asciiuppercase 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.asciilowercase)] if uppercase: required.append(random.choice(string.asciiuppercase)) if digits: required.append(random.choice(string.digits)) if special: required.append(random.choice("!@#$%^&*")) pwdlist = list(password[:length - len(required)] + ''.join(required)) random.shuffle(pwdlist) return ''.join(pwdlist)
print("=" * 40) print(" 🔐 PASSWORD GENERATOR") print("=" * 40)
for i in range(5): pwd = generate_password(16) print(f" {i+1}. {pwd}")
python id="py27ex1" import time from datetime import datetime
def runscheduler(task, intervalseconds, maxruns=5): """Simple task scheduler""" run = 0 while run < maxruns: run += 1 timestamp = datetime.now().strftime("%H:%M:%S") print(f" [{timestamp}] Run {run}: ", end="") task() time.sleep(intervalseconds)
# Example task def checkstatus(): print("System status: OK ✅")
# Run every 3 seconds, 5 times
# runscheduler(checkstatus, 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(existok=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.diskusage() returns:
A) CPU usage B) Disk total/used/free C) Memory usage D) Network usage
Answer: B
Q8: string.asciiletters 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! 🚀