Automate Daily Tasks with Python Scripts (6 Examples)
As software engineers, system administrators, and data analysts, we frequently find ourselves drowning in repetitive digital chores: organizing cluttered download folders, renaming hundreds of batch image files, backing up local databases, monitoring server endpoints, and parsing server log files. Manual execution not only wastes precious engineering hours but also introduces human error.
Python is the ultimate glue language for automation due to its rich standard library (os, shutil, pathlib, subprocess, smtplib) and powerful third-party ecosystem. This comprehensive tutorial explores 6 practical, production-ready Python automation scripts** designed to eliminate repetitive daily workflows.
1. Automated File Organizer by Extension
Cluttered Downloads directories slow down productivity. This script scans a target directory and automatically sorts files into structured subfolders (Images, Documents, Archives, Code) based on their file extensions.
import os
import shutil
from pathlib import Path
def organize_downloads(target_dir: str):
path = Path(target_dir)
if not path.exists():
print(f"Directory {target_dir} does not exist.")
return
# Define mapping of extensions to category folders
extensions_map = {
'Images': ['.jpg', '.jpeg', '.png', '.gif', '.svg'],
'Documents': ['.pdf', '.docx', '.txt', '.xlsx', '.pptx', '.csv'],
'Archives': ['.zip', '.tar', '.gz', '.rar'],
'Code': ['.py', '.js', '.html', '.css', '.json', '.sh']
}
for file_path in path.iterdir():
if file_path.is_file():
ext = file_path.suffix.lower()
moved = False
for category, exts in extensions_map.items():
if ext in exts:
dest_folder = path / category
dest_folder.mkdir(exist_ok=True)
shutil.move(str(file_path), str(dest_folder / file_path.name))
print(f"Moved: {file_path.name} -> {category}/")
moved = True
break
if not moved:
other_folder = path / 'Others'
other_folder.mkdir(exist_ok=True)
shutil.move(str(file_path), str(other_folder / file_path.name))
# Example invocation
# organize_downloads("/path/to/Downloads")
2. Batch Image Resizer and Compressor
Preparing images for web publishing or machine learning datasets often requires resizing large batches of photos. Using Pillow (PIL), this script processes entire folders instantly.
from PIL import Image
from pathlib import Path
def batch_resize_images(source_dir: str, output_dir: str, max_width: int = 1200):
src_path = Path(source_dir)
out_path = Path(output_dir)
out_path.mkdir(parents=True, exist_ok=True)
for img_file in src_path.glob('*.*'):
if img_file.suffix.lower() in ['.jpg', '.jpeg', '.png']:
try:
with Image.open(img_file) as img:
width_percent = (max_width / float(img.size[0]))
new_height = int(float(img.size[1]) * float(width_percent))
resized_img = img.resize((max_width, new_height), Image.Resampling.LANCZOS)
dest_path = out_path / img_file.name
resized_img.save(dest_path, optimize=True, quality=85)
print(f"Resized and saved: {img_file.name}")
except Exception as e:
print(f"Failed to process {img_file.name}: {e}")
# Example invocation
# batch_resize_images("./raw_images", "./optimized_images", 800)
3. CPU and Disk Health Monitor Alert
Prevent server outages by monitoring local system resource utilization (psutil) and logging warnings when thresholds are exceeded.
import psutil
import time
def check_system_health(cpu_threshold: float = 85.0, disk_threshold: float = 90.0):
cpu_usage = psutil.cpu_percent(interval=1)
disk_usage = psutil.disk_usage('/')
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] CPU Usage: {cpu_usage}% | Disk Usage: {disk_usage.percent}%")
if cpu_usage > cpu_threshold:
print(f"⚠️ WARNING: High CPU utilization detected: {cpu_usage}%")
if disk_usage.percent > disk_threshold:
print(f"⚠️ WARNING: Disk space critically low: {disk_usage.percent}%")
# Example invocation
# check_system_health()
4. Automated Timestamped Directory Backup
Secure your important project code or databases by generating compressed .zip archives with unique timestamps.
import shutil
from datetime import datetime
from pathlib import Path
def create_backup(source_dir: str, backup_dest: str):
src = Path(source_dir)
dest = Path(backup_dest)
dest.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
archive_name = dest / f"backup_{src.name}_{timestamp}"
shutil.make_archive(str(archive_name), 'zip', str(src))
print(f"✅ Backup successfully created at: {archive_name}.zip")
# Example invocation
# create_backup("./my_project", "./backups")
5. Website Uptime and API Health Checker
Automate checking whether your production web applications or REST APIs return valid 200 OK responses.
import requests
def check_website_uptime(url: str):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
print(f"🟢 {url} is UP (Status: 200 OK)")
else:
print(f"🟡 {url} returned status code: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"🔴 {url} is DOWN! Error: {e}")
# Example invocation
# check_website_uptime("https://codecrown.in")
6. Log File Error Extractor
Quickly scan massive server access or application logs to extract and summarize critical error occurrences.
from pathlib import Path
def extract_errors_from_log(log_filepath: str):
path = Path(log_filepath)
if not path.exists():
print("Log file not found.")
return
error_count = 0
print(f"--- Scanning {path.name} for Errors ---")
with open(path, 'r', encoding='utf-8') as file:
for line_num, line in enumerate(file, 1):
if "ERROR" in line or "CRITICAL" in line:
print(f"Line {line_num}: {line.strip()}")
error_count += 1
print(f"--- Scan Complete. Total errors found: {error_count} ---")
# Example invocation
# extract_errors_from_log("./server.log")
Conclusion
By leveraging Python's versatile standard libraries and robust packages like requests, psutil, and Pillow, developers can automate routine file management, system monitoring, and backup workflows efficiently, freeing up time for complex engineering challenges.