Whether you are a software developer, student, digital marketer, or tech enthusiast, repetitive digital chores silently steal hours of your week. Organizing messy downloads, checking server uptimes, resizing bulk images, and gathering web data are tasks that computers should handle directly in the background.
Python remains the undisputed champion of workflow automation in 2026 due to its readability, comprehensive standard library, and massive open-source ecosystem. In this guide, we have compiled 10 practical, production-ready Python automation scripts with clean code examples that you can start using today.
Prerequisites and Setup
Before running these scripts, ensure you have Python 3.10+ installed on your system. If you are setting up your development environment on Windows, check our comprehensive walkthrough on How to install Python on Windows.
To write, debug, and manage your scripts productively, we recommend using VS Code equipped with top developer extensions - see our guide on 10 VS Code Extensions that make your coding Better.
You can install the third-party libraries used in these examples with a single command:
pip install requests beautifulsoup4 pillow pyperclip pypdf psutil
1. Instant Public IP, Local IP and Geolocation Fetcher
Need to quickly inspect your network connectivity, discover your machine's private IPv4 address, or check your public geolocation details programmatically? This script queries your local network interface and retrieves public metadata using lightweight REST endpoints.
For deeper network socket programming, check out our earlier tutorial on How to Get IP Address Information Using Python.
import socket
import requests
def get_network_details():
# 1. Fetch Local Hostname and Local IP Address
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
print("=" * 45)
print(f"Device Hostname : {hostname}")
print(f"Local IPv4 : {local_ip}")
# 2. Fetch Public IP and Geolocation Details
try:
response = requests.get("https://ipapi.co/json/", timeout=5)
if response.status_code == 200:
data = response.json()
print(f"Public IP : {data.get('ip')}")
print(f"City / Region : {data.get('city')}, {data.get('region')}")
print(f"Country and ISP : {data.get('country_name')} ({data.get('org')})")
else:
print("[Warning] Could not retrieve public IP metadata.")
except requests.RequestException as err:
print(f"[Error] Network Error: {err}")
print("=" * 45)
if __name__ == "__main__":
get_network_details()
External reference: Learn more about socket operations in the Official Python socket documentation.
2. Smart Downloads and Desktop File Auto-Organizer
Is your Downloads or Desktop folder cluttered with hundreds of mixed files? This script automatically categorizes files based on their extensions and sorts them into dedicated subdirectories.
import os
import shutil
from pathlib import Path
# Target directory to organize
TARGET_DIR = Path.home() / "Downloads"
# Extension category mapping
FILE_CATEGORIES = {
"Documents": [".pdf", ".docx", ".doc", ".txt", ".xlsx", ".pptx", ".csv"],
"Images": [".png", ".jpg", ".jpeg", ".webp", ".svg", ".gif"],
"Videos": [".mp4", ".mkv", ".mov", ".avi"],
"Audio": [".mp3", ".wav", ".aac", ".flac"],
"Archives": [".zip", ".rar", ".tar", ".gz", ".7z"],
"Code_and_Executables": [".exe", ".msi", ".py", ".js", ".html", ".css", ".json"]
}
def organize_folder(folder_path: Path):
if not folder_path.exists():
print(f"Path does not exist: {folder_path}")
return
for item in folder_path.iterdir():
if item.is_file():
extension = item.suffix.lower()
moved = False
for category, extensions in FILE_CATEGORIES.items():
if extension in extensions:
dest_folder = folder_path / category
dest_folder.mkdir(exist_ok=True)
shutil.move(str(item), str(dest_folder / item.name))
print(f"Moved: {item.name} -> {category}/")
moved = True
break
if not moved and extension != "":
other_folder = folder_path / "Others"
other_folder.mkdir(exist_ok=True)
shutil.move(str(item), str(other_folder / item.name))
print(f"Moved: {item.name} -> Others/")
if __name__ == "__main__":
organize_folder(TARGET_DIR)
3. Automated Website Uptime and HTTP Response Status Monitor
If you manage personal blogs, client websites, or APIs, running an automated heartbeat monitor helps catch outages before your users notice.
import time
import requests
WEBSITES_TO_MONITOR = [
"https://ilabacademy.blogspot.com",
"https://google.com",
"https://github.com"
]
def check_websites():
print(f"Checking site status at {time.strftime('%Y-%m-%d %H:%M:%S')}...")
for site in WEBSITES_TO_MONITOR:
try:
start_time = time.time()
res = requests.get(site, timeout=10)
latency = round((time.time() - start_time) * 1000, 2)
if res.status_code == 200:
print(f"[UP] {site} - Status: {res.status_code} ({latency}ms)")
else:
print(f"[WARN] {site} - Status: {res.status_code} ({latency}ms)")
except requests.RequestException as e:
print(f"[DOWN] {site} - Error: {e}")
if __name__ == "__main__":
check_websites()
For more details on handling timeouts and sessions, consult the Requests Documentation.
4. Bulk Image Resizer and Format Converter (WebP / JPEG)
Large, unoptimized images slow down web applications and consume excessive disk space. This script scans an input folder, compresses images, and converts them to modern .webp or optimized .jpg formats.
from pathlib import Path
from PIL import Image
def optimize_images(input_dir: str, output_dir: str, max_width: int = 1200, quality: int = 80):
src_path = Path(input_dir)
out_path = Path(output_dir)
out_path.mkdir(parents=True, exist_ok=True)
supported_formats = {".jpg", ".jpeg", ".png", ".bmp"}
for file in src_path.iterdir():
if file.suffix.lower() in supported_formats:
try:
with Image.open(file) as img:
# Convert RGBA to RGB for JPEG/WebP compatibility
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
# Proportional resize if larger than max_width
if img.width > max_width:
ratio = max_width / float(img.width)
new_height = int((float(img.height) * float(ratio)))
img = img.resize((max_width, new_height), Image.Resampling.LANCZOS)
output_file = out_path / f"{file.stem}.webp"
img.save(output_file, "WEBP", quality=quality, optimize=True)
print(f"Optimized: {file.name} -> {output_file.name}")
except Exception as e:
print(f"Failed to process {file.name}: {e}")
if __name__ == "__main__":
optimize_images("./raw_images", "./optimized_images")
5. Automated Web Scraper with CSV Export
Extracting headlines, tabular statistics, or product pricing is straightforward with BeautifulSoup and requests.
import csv
import requests
from bs4 import BeautifulSoup
def scrape_top_headlines(url: str, output_csv: str):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Failed to fetch page: {response.status_code}")
return
soup = BeautifulSoup(response.text, "html.parser")
headlines = []
# Extract h2 and h3 elements (standard article titles)
for tag in soup.find_all(["h2", "h3"]):
text = tag.get_text(strip=True)
if text and len(text) > 10:
headlines.append([text])
with open(output_csv, mode="w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Extracted Headline"])
writer.writerows(headlines)
print(f"Successfully scraped {len(headlines)} items to {output_csv}")
if __name__ == "__main__":
scrape_top_headlines("https://ilabacademy.blogspot.com", "blog_headlines.csv")
External reference: Dive deeper with the Beautiful Soup 4 Official Documentation.
6. Clipboard Text Cleaner and Markdown Link Formatter
When drafting documentation, copying raw URLs or unformatted text is tedious. This script reads text straight from your clipboard, cleans excessive whitespace, and wraps it into Markdown link or bulleted list format.
import pyperclip
import re
def clean_clipboard_to_markdown():
raw_text = pyperclip.paste()
if not raw_text.strip():
print("Clipboard is empty.")
return
# Check if clipboard contains a URL
url_pattern = re.compile(r"^https?://[^\s]+$")
if url_pattern.match(raw_text.strip()):
url = raw_text.strip()
formatted = f"[Link Title]({url})"
else:
# Format multi-line list into clean markdown bullet points
lines = [line.strip() for line in raw_text.splitlines() if line.strip()]
formatted = "\n".join([f"- {line}" for line in lines])
pyperclip.copy(formatted)
print("Cleaned and updated clipboard with Markdown formatting:")
print(formatted)
if __name__ == "__main__":
clean_clipboard_to_markdown()
7. Automated Email Notification Sender (SMTP with SSL)
Send automated logs, daily digests, or backup alerts directly to your inbox using Python's built-in smtplib.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_alert_email(subject: str, body_html: str, to_email: str):
smtp_server = "smtp.gmail.com"
smtp_port = 465
sender_email = "your_email@gmail.com"
sender_password = "your_app_password" # Use Google App Passwords
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = sender_email
msg["To"] = to_email
msg.attach(MIMEText(body_html, "html"))
try:
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
server.login(sender_email, sender_password)
server.sendmail(sender_email, to_email, msg.as_string())
print(f"Alert email sent to {to_email}")
except Exception as e:
print(f"Failed to send email: {e}")
if __name__ == "__main__":
html_content = "<h2>Daily System Report</h2><p>All automated tasks finished with <strong>status: SUCCESS</strong>.</p>"
print("Configure your SMTP credentials to test automated email sending.")
8. Bulk PDF Text and Table Extractor (pypdf)
Extracting paragraphs and data tables from multiple PDF files manually is exhausting. This script reads any PDF and outputs clean plaintext.
from pathlib import Path
from pypdf import PdfReader
def extract_text_from_pdf(pdf_path: str, output_txt: str):
path = Path(pdf_path)
if not path.exists():
print(f"File not found: {pdf_path}")
return
reader = PdfReader(path)
full_text = []
print(f"Processing '{path.name}' ({len(reader.pages)} pages)...")
for idx, page in enumerate(reader.pages):
page_text = page.extract_text()
if page_text:
full_text.append(f"--- Page {idx + 1} ---\n{page_text}")
with open(output_txt, "w", encoding="utf-8") as f:
f.write("\n\n".join(full_text))
print(f"Text extracted successfully into {output_txt}")
if __name__ == "__main__":
print("Provide a sample PDF path to extract text.")
9. AI-Powered Text Summarizer and Data Categorizer
Leveraging generative AI APIs inside lightweight Python scripts allows you to automate text summarization, code review, and sentiment analysis at scale.
For more tools that enhance coding productivity, explore our curated list of 11 Practical AI Tools for Coders That Actually Save Time and discover how autonomous agents are transforming modern work in 11 Practical Ways AI Agents Help You Today.
import os
import requests
def summarize_with_ai(prompt_text: str) -> str:
api_key = os.getenv("GEMINI_API_KEY", "YOUR_API_KEY_HERE")
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={api_key}"
payload = {
"contents": [{
"parts": [{"text": f"Summarize the following text in 3 crisp bullet points with key takeaways:\n\n{prompt_text}"}]
}]
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
result = response.json()
summary = result["candidates"][0]["content"]["parts"][0]["text"]
return summary
else:
return f"Error: {response.status_code} - {response.text}"
if __name__ == "__main__":
sample_article = "Python is an interpreted, high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically typed and garbage-collected."
print("Add your API key to automate AI summarization on your datasets.")
10. System Resource Monitor and Discord/Telegram Webhook
Server administrators and heavy power users need to know when background tasks consume excessive memory or CPU. This script checks resource thresholds and fires a webhook alert.
import psutil
import requests
DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/YOUR_WEBHOOK_URL"
def monitor_system(cpu_threshold=85.0, ram_threshold=90.0):
cpu_usage = psutil.cpu_percent(interval=1)
ram_usage = psutil.virtual_memory().percent
disk_usage = psutil.disk_usage("/").percent
print(f"CPU: {cpu_usage}% | RAM: {ram_usage}% | Disk: {disk_usage}%")
if cpu_usage > cpu_threshold or ram_usage > ram_threshold:
alert_msg = {
"content": f"[High Resource Alert]\n- CPU: `{cpu_usage}%`\n- RAM: `{ram_usage}%`\n- Disk: `{disk_usage}%`"
}
try:
requests.post(DISCORD_WEBHOOK_URL, json=alert_msg, timeout=5)
print("Webhook alert dispatched!")
except requests.RequestException as e:
print(f"Failed to send webhook: {e}")
if __name__ == "__main__":
monitor_system()
How to Schedule Your Python Scripts Automatically
To unlock true automation, your scripts should run without manual intervention:
- On Windows (Task Scheduler):
- Open Task Scheduler > Create Basic Task.
- Set the trigger (e.g., Daily at 08:00 AM or On Startup).
- In Action, select Start a Program, enter
python.exeas the program and your script path in Add arguments.
- On Linux / macOS (Cron Jobs):
- Open the crontab editor:
crontab -e - Add a schedule (e.g., run every day at 9 AM):
0 9 * * * /usr/bin/python3 /path/to/your_script.py >> /path/to/logfile.log 2>&1
- Open the crontab editor:
Summary and Next Steps
Automating small, repetitive routines with Python compounds into massive time savings over time. Start by picking one script from this guide - such as the Downloads File Organizer or Uptime Monitor - and customize it to your personal environment.
Which automation script are you planning to deploy first? Let us know in the comments below, and don't forget to bookmark iLab Academy for more cutting-edge programming tutorials, developer tools, and AI insights!
0 Comments