Python Automation Scripts for Daily Tasks
Automation is most useful when a task is repetitive, predictable, and easy to verify. The examples below focus on those boundaries rather than trying to turn every task into a large system.
File Organization Scripts
1. Automatic File Organizer
Organize downloads folder automatically:
import os
import shutil
from pathlib import Path
def organize_downloads():
downloads_path = Path.home() / 'Downloads'
# Define file type mappings
file_types = {
'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
'documents': ['.pdf', '.doc', '.docx', '.txt', '.rtf'],
'videos': ['.mp4', '.avi', '.mov', '.wmv', '.flv'],
'audio': ['.mp3', '.wav', '.flac', '.aac'],
'archives': ['.zip', '.rar', '.7z', '.tar', '.gz'],
'code': ['.py', '.js', '.html', '.css', '.json', '.xml']
}
for file_path in downloads_path.iterdir():
if file_path.is_file():
file_extension = file_path.suffix.lower()
# Find the appropriate folder
target_folder = None
for folder_name, extensions in file_types.items():
if file_extension in extensions:
target_folder = folder_name
break
if target_folder:
# Create folder if it doesn't exist
folder_path = downloads_path / target_folder
folder_path.mkdir(exist_ok=True)
# Move file
shutil.move(str(file_path), str(folder_path / file_path.name))
print(f"Moved {file_path.name} to {target_folder}/")
if __name__ == "__main__":
organize_downloads()
2. Duplicate File Finder
Find duplicate files without deleting anything automatically:
import hashlib
from collections import defaultdict
from pathlib import Path
def find_duplicates(directory):
hashes = defaultdict(list)
for file_path in Path(directory).rglob('*'):
if file_path.is_file():
digest = hashlib.sha256()
with file_path.open('rb') as source:
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
hashes[digest.hexdigest()].append(file_path)
# Find duplicates
duplicates = {hash_val: paths for hash_val, paths in hashes.items() if len(paths) > 1}
return duplicates
# Usage
duplicates = find_duplicates('/path/to/directory')
for paths in duplicates.values():
print("Review duplicate group:", *paths, sep="\n ")
Review the output before moving anything to the operating system’s trash. Hash equality is strong evidence of identical bytes, but it does not tell you which copy is safe to remove.
Web Scraping Automation
3. News Headlines Scraper
Get daily news headlines automatically:
import requests
from bs4 import BeautifulSoup
import schedule
import time
def scrape_news():
url = 'https://news.ycombinator.com'
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
headlines = []
for story in soup.select('.titleline > a'):
title = story.get_text()
link = story.get('href')
headlines.append({'title': title, 'link': link})
# Save to file
with open('daily_news.txt', 'w', encoding='utf-8') as f:
f.write("Daily Tech News\n")
f.write("=" * 50 + "\n\n")
for i, headline in enumerate(headlines[:10], 1):
f.write(f"{i}. {headline['title']}\n")
f.write(f" {headline['link']}\n\n")
print("News scraped and saved!")
# Schedule to run daily at 9 AM
schedule.every().day.at("09:00").do(scrape_news)
while True:
schedule.run_pending()
time.sleep(60)
4. Price Monitor
Monitor product prices and get alerts:
import requests
from bs4 import BeautifulSoup
import smtplib
import os
from email.mime.text import MIMEText
def check_price(url, target_price, email):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
# Extract price (adjust selector based on website)
price_element = soup.find('span', class_='price')
if price_element:
current_price = float(price_element.get_text().replace('$', '').replace(',', ''))
if current_price <= target_price:
send_price_alert(email, url, current_price, target_price)
def send_price_alert(email, url, current_price, target_price):
msg = MIMEText(f"""
Price Alert!
The product you're monitoring has dropped to ${current_price}
Target price: ${target_price}
Product URL: {url}
""")
msg['Subject'] = 'Price Alert!'
msg['From'] = '[email protected]'
msg['To'] = email
# Send email (configure SMTP settings)
smtp_user = os.environ['SMTP_USER']
smtp_password = os.environ['SMTP_PASSWORD']
msg['From'] = smtp_user
with smtplib.SMTP('smtp.gmail.com', 587, timeout=10) as server:
server.starttls()
server.login(smtp_user, smtp_password)
server.send_message(msg)
# Usage
check_price('https://example.com/product', 100.0, '[email protected]')
Data Processing Automation
5. CSV Data Processor
Process and clean CSV files automatically:
import pandas as pd
import numpy as np
from datetime import datetime
def process_csv(input_file, output_file):
# Read CSV
df = pd.read_csv(input_file)
# Data cleaning
df = df.dropna() # Remove rows with missing values
df = df.drop_duplicates() # Remove duplicates
# Data transformation
if 'date' in df.columns:
df['date'] = pd.to_datetime(df['date'])
if 'price' in df.columns:
df['price'] = pd.to_numeric(df['price'], errors='coerce')
# Add calculated columns
if 'quantity' in df.columns and 'price' in df.columns:
df['total'] = df['quantity'] * df['price']
# Save processed data
df.to_csv(output_file, index=False)
print(f"Processed {len(df)} rows and saved to {output_file}")
# Usage
process_csv('raw_data.csv', 'processed_data.csv')
6. Database Backup Script
Automated database backups:
import subprocess
import os
from datetime import datetime
def backup_database(db_name, credentials_file, backup_dir):
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_file = f"{backup_dir}/{db_name}_backup_{timestamp}.sql"
# Create backup directory if it doesn't exist
os.makedirs(backup_dir, exist_ok=True)
# Run mysqldump command
cmd = [
'mysqldump',
f'--defaults-extra-file={credentials_file}',
'--single-transaction',
'--routines',
'--triggers',
db_name
]
with open(backup_file, 'w') as f:
subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, check=True, text=True)
print(f"Database backup created: {backup_file}")
# Compress backup
subprocess.run(['gzip', '--', backup_file], check=True)
print(f"Backup compressed: {backup_file}.gz")
# Usage
backup_database('myapp', '/secure/path/mysql-client.cnf', '/backups')
The credentials file should be readable only by the account running the backup. Keeping a password out of command-line arguments prevents it from appearing in ordinary process listings.
System Monitoring
7. System Health Monitor
Monitor system resources:
import psutil
import time
import json
from datetime import datetime
def monitor_system():
while True:
# Collect system metrics
cpu_percent = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
metrics = {
'timestamp': datetime.now().isoformat(),
'cpu_percent': cpu_percent,
'memory_percent': memory.percent,
'memory_available_gb': memory.available / (1024**3),
'disk_percent': disk.percent,
'disk_free_gb': disk.free / (1024**3)
}
# Log metrics
with open('system_metrics.json', 'a') as f:
f.write(json.dumps(metrics) + '\n')
# Alert if thresholds exceeded
if cpu_percent > 80:
print(f"High CPU usage: {cpu_percent}%")
if memory.percent > 85:
print(f"High memory usage: {memory.percent}%")
if disk.percent > 90:
print(f"Low disk space: {disk.percent}% used")
time.sleep(60) # Check every minute
# Run monitoring
monitor_system()
Email Automation
8. Automated Email Reports
Send daily reports via email:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pandas as pd
from datetime import datetime, timedelta
def generate_daily_report():
# Generate report data
yesterday = datetime.now() - timedelta(days=1)
# Your data processing logic here
report_data = {
'date': yesterday.strftime('%Y-%m-%d'),
'total_users': 1250,
'new_signups': 45,
'active_users': 890,
'revenue': 12500.50
}
return report_data
def send_email_report(report_data, recipient_email):
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = recipient_email
msg['Subject'] = f"Daily Report - {report_data['date']}"
# Create HTML email body
html_body = f"""
<html>
<body>
<h2>Daily Report - {report_data['date']}</h2>
<table border="1" style="border-collapse: collapse;">
<tr><td><strong>Metric</strong></td><td><strong>Value</strong></td></tr>
<tr><td>Total Users</td><td>{report_data['total_users']}</td></tr>
<tr><td>New Signups</td><td>{report_data['new_signups']}</td></tr>
<tr><td>Active Users</td><td>{report_data['active_users']}</td></tr>
<tr><td>Revenue</td><td>${report_data['revenue']}</td></tr>
</table>
</body>
</html>
"""
msg.attach(MIMEText(html_body, 'html'))
# Send email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('[email protected]', 'your-password')
server.send_message(msg)
server.quit()
print("Daily report sent successfully!")
# Usage
report = generate_daily_report()
send_email_report(report, '[email protected]')
Conclusion
These automation scripts can save you significant time and reduce manual errors. Start with simple scripts and gradually build more complex automation systems. Remember to always test your scripts thoroughly before deploying them in production.
Tips for Effective Automation
- Start small: Begin with simple, repetitive tasks
- Test thoroughly: Always test scripts in a safe environment
- Add logging: Include proper logging for debugging
- Handle errors: Implement proper error handling
- Document everything: Keep your code well-documented
- Schedule appropriately: Use cron jobs or task schedulers for regular tasks
Resources
Automation is not about replacing human intelligence, but about freeing up time for more creative and strategic work.