Python for Automation: A Practical Guide with Scripts and Examples

Python Logo

Python's simplicity, readability, and extensive collection of libraries make it the go-to language for automation. From simple file organization to complex web scraping and data processing, Python can handle repetitive tasks, saving you time and reducing errors. This guide explores practical examples of automation scripts you can build today.

1. File System Automation: Organize Your Digital Life

Managing files and folders is a common, tedious task. Python's built-in os and shutil libraries provide a powerful way to automate file operations.

Example: A Script to Organize Files by Extension

This script scans a directory and moves files into subdirectories named after their file extensions (e.g., all `.pdf` files go into a 'pdf' folder).

import os
import shutil

# The directory to organize
TARGET_DIR = '/path/to/your/downloads'

# Get all file names in the directory
files = [f for f in os.listdir(TARGET_DIR) if os.path.isfile(os.path.join(TARGET_DIR, f))]

for file in files:
    # Get the file extension
    file_ext = file.split('.')[-1].lower()

    # Create a directory for the extension if it doesn't exist
    ext_dir = os.path.join(TARGET_DIR, file_ext)
    if not os.path.exists(ext_dir):
        os.makedirs(ext_dir)

    # Move the file
    shutil.move(os.path.join(TARGET_DIR, file), os.path.join(ext_dir, file))

print(f'Successfully organized {len(files)} files.')

2. Web Scraping: Extracting Data from the Web

Web scraping automates the process of collecting data from websites. The requests library fetches web pages, and BeautifulSoup parses the HTML, making it easy to find and extract the information you need.

Example: Scrape Blog Titles from a Website

import requests
from bs4 import BeautifulSoup

URL = 'https://example-news-website.com/tech'

try:
    response = requests.get(URL)
    response.raise_for_status() # Raise an exception for bad status codes

    soup = BeautifulSoup(response.text, 'html.parser')

    # Find all h2 elements with a specific class (adjust selector for the target site)
    headlines = soup.find_all('h2', class_='post-title')

    for headline in headlines:
        print(headline.get_text().strip())

except requests.exceptions.RequestException as e:
    print(f'Error fetching URL: {e}')

3. Automating Spreadsheets with Pandas

The pandas library is a powerhouse for data manipulation and analysis. It can read from various sources, including Excel files, and perform complex operations with just a few lines of code.

Example: Generate a Sales Summary from an Excel File

import pandas as pd

# Read the Excel file
df = pd.read_excel('sales_data.xlsx')

# Calculate total revenue
total_revenue = (df['Units Sold'] * df['Price Per Unit']).sum()

# Find the best-selling product
best_selling_product = df.groupby('Product')['Units Sold'].sum().idxmax()

print(f'Total Revenue: ${total_revenue:,.2f}')
print(f'Best-Selling Product: {best_selling_product}')

4. Sending Automated Emails

Python's standard library includes modules for sending emails. The smtplib module handles the connection to the email server, while the email module helps construct the messages.

Example: Send a Daily Status Report

import smtplib
from email.mime.text import MIMEText

SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
SENDER_EMAIL = 'your_email@example.com'
SENDER_PASSWORD = 'your_password'
RECIPIENT_EMAIL = 'recipient@example.com'

# Create the email message
subject = 'Daily Status Report'
body = 'All systems are running smoothly.'
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = SENDER_EMAIL
msg['To'] = RECIPIENT_EMAIL

try:
    with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
        server.starttls()
        server.login(SENDER_EMAIL, SENDER_PASSWORD)
        server.send_message(msg)
        print('Email sent successfully!')
except Exception as e:
    print(f'Failed to send email: {e}')

Comments