File Automation with pathlib
from pathlib import Path
import shutil
downloads = Path.home() / "Downloads"
categories = {
".pdf": "Documents",
".jpg": "Images", ".jpeg": "Images", ".png": "Images",
".mp4": "Videos",
".zip": "Archives",
}
for file in downloads.iterdir():
if file.is_file() and file.suffix.lower() in categories:
dest_dir = downloads / categories[file.suffix.lower()]
dest_dir.mkdir(exist_ok=True)
shutil.move(str(file), dest_dir / file.name)
print(f"Moved {file.name}")Scheduling Tasks
import schedule
import time
def daily_report():
print("Generating report...")
schedule.every().day.at("09:00").do(daily_report)
schedule.every().hour.do(lambda: print("Heartbeat"))
while True:
schedule.run_pending()
time.sleep(60)Sending Emails
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(to, subject, body, smtp_pass):
msg = MIMEMultipart()
msg["From"] = "you@gmail.com"
msg["To"] = to
msg["Subject"] = subject
msg.attach(MIMEText(body, "html"))
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login("you@gmail.com", smtp_pass)
server.sendmail("you@gmail.com", to, msg.as_string())Excel with openpyxl
import openpyxl
from openpyxl.styles import Font, PatternFill
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Report"
headers = ["Product", "Units", "Revenue"]
for col, h in enumerate(headers, 1):
cell = ws.cell(row=1, column=col, value=h)
cell.font = Font(bold=True)
data = [("Widget A", 150, 7500), ("Widget B", 230, 11500)]
for row_idx, row_data in enumerate(data, 2):
for col_idx, value in enumerate(row_data, 1):
ws.cell(row=row_idx, column=col_idx, value=value)
wb.save("report.xlsx")Automation: Let Python Do the Boring Work
Automation is one of Python's most practical uses — replacing repetitive manual tasks (renaming files, sending reports, cleaning data) with a script you run once and reuse forever. The standard-library tools cover most needs.
| Task | Module |
|---|---|
| files & folders | pathlib, shutil |
| run other programs | subprocess |
| scheduling | OS cron / Task Scheduler |
| web/API tasks | requests |
from pathlib import Path
# rename every .txt in a folder to .md
for file in Path("notes").glob("*.txt"):
file.rename(file.with_suffix(".md"))
Use pathlib, not string paths: Path("a") / "b" / "c.txt" builds paths that work on every OS, with methods like .glob(), .exists(), and .rename() — far cleaner than fragile os.path.join string juggling. Golden rule of destructive automation: a script that renames, moves, or deletes files can wreck data fast — test on a copy first, print what it would do (a dry run) before actually doing it, and back up. Scheduling: to run a script automatically (nightly cleanup, hourly report), register it with your OS scheduler (cron on Linux/macOS, Task Scheduler on Windows) rather than leaving a Python loop running. Use subprocess.run([...], check=True) to invoke other command-line tools safely.
🏋️ Practical Exercise
Automate routine tasks:
- Use
pathlibto list every.txtfile in a folder. - Rename or move files into subfolders based on their extension.
- Schedule a function to run every few seconds with the
schedulelibrary (or a loop withtime.sleep). - Write a script that appends a timestamped line to a log file each run.
🔥 Challenge Exercise
Write a “downloads organizer” that scans a folder and moves files into category subfolders (Images, Documents, Archives, Other) based on their extension, creating folders as needed and avoiding name collisions. Make it safe to run repeatedly. Bonus: schedule it to run periodically and email yourself a summary of how many files were moved.
📋 Summary
- Python excels at automating repetitive file, data, and communication tasks.
pathliboffers a clean, object-oriented API for filesystem work.- Schedule recurring jobs with the
schedulelibrary, a loop, or OS tools like cron. - Libraries like
openpyxl(Excel) andsmtplib(email) extend automation reach. - Make scripts idempotent and add logging so reruns are safe and observable.
- Wrap risky steps in error handling so failures are reported, not hidden.
Interview Questions on Automation
- What kinds of tasks are good candidates for automation with Python?
- Why is
pathlibpreferred overos.pathfor file work? - How do you schedule recurring tasks in Python?
- What libraries help automate Excel or email?
- How do you make an automation script safe to run repeatedly (idempotent)?
- How do you handle errors so an automation does not silently fail?
- What is the difference between scheduling in-process and using cron / Task Scheduler?
Related Topics
FAQ
pathlib instead of os.path? +pathlib represents paths as objects with intuitive methods and the / operator for joining (folder / "file.txt"). It is more readable and less error-prone than string-based os.path functions.
For simple cases use the schedule library or a while loop with time.sleep. For reliable, system-level scheduling, use cron on Linux/macOS or Task Scheduler on Windows to run the script at set times.
Design it to be idempotent: check whether an action is already done before doing it (e.g. skip files already moved), avoid overwriting data unintentionally, and log each action so you can audit what happened.
Yes. Use openpyxl or pandas for Excel files, and smtplib with email for sending mail. For richer Office automation there are libraries like xlsxwriter and provider-specific email APIs.
