Operations 19 min read

9 Practical Python Automation Scenarios with Sample Scripts

This article presents nine practical Python automation scenarios—including file management, web scraping, text processing, email handling, Excel manipulation, database interaction, social media posting, system task scheduling, and image editing—each accompanied by clear script examples and explanations to help readers streamline repetitive tasks efficiently.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
9 Practical Python Automation Scenarios with Sample Scripts

1. File Management Automation

This section shows how to sort files by extension, delete empty folders, and rename multiple files using Python.

# Python script to sort files in a directory by their extension
import os
from shutil import move

def sort_files(directory_path):
    for filename in os.listdir(directory_path):
        if os.path.isfile(os.path.join(directory_path, filename)):
            file_extension = filename.split('.')[-1]
            destination_directory = os.path.join(directory_path, file_extension)
            if not os.path.exists(destination_directory):
                os.makedirs(destination_directory)
            move(os.path.join(directory_path, filename), os.path.join(destination_directory, filename))

The script organizes files into sub‑folders named after their extensions, which is useful for cleaning download folders.

# Python script to remove empty folders in a directory
import os

def remove_empty_folders(directory_path):
    for root, dirs, files in os.walk(directory_path, topdown=False):
        for folder in dirs:
            folder_path = os.path.join(root, folder)
            if not os.listdir(folder_path):
                os.rmdir(folder_path)

This script walks a directory tree and deletes any folder that contains no files.

# Python script to rename multiple files in a directory
import os

def rename_files(directory_path, old_name, new_name):
    for filename in os.listdir(directory_path):
        if old_name in filename:
            new_filename = filename.replace(old_name, new_name)
            os.rename(os.path.join(directory_path, filename), os.path.join(directory_path, new_filename))

It replaces a specified substring in each filename with a new string.

2. Web Scraping with Python

Examples demonstrate extracting data from a website and downloading images in bulk.

# Python script for web scraping to extract data from a website
import requests
from bs4 import BeautifulSoup

def scrape_data(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    # Your code here to extract relevant data from the website

Using requests and BeautifulSoup , the script fetches HTML and parses it for custom data extraction.

# Python script to download images in bulk from a website
import requests

def download_images(url, save_directory):
    response = requests.get(url)
    if response.status_code == 200:
        images = response.json()  # Assuming the API returns a JSON array of image URLs
        for index, image_url in enumerate(images):
            image_response = requests.get(image_url)
            if image_response.status_code == 200:
                with open(f"{save_directory}/image_{index}.jpg", "wb") as f:
                    f.write(image_response.content)

This script assumes an API that returns image URLs, then saves each image locally.

# Python script to automate form submissions on a website
import requests

def submit_form(url, form_data):
    response = requests.post(url, data=form_data)
    if response.status_code == 200:
        # Your code here to handle the response after form submission
        pass

It posts form data to a given URL and checks for a successful response.

3. Text Processing

Utilities for counting words, find‑and‑replace, and generating random text.

# Python script to count words in a text file
def count_words(file_path):
    with open(file_path, 'r') as f:
        text = f.read()
        word_count = len(text.split())
    return word_count
# Python script to find and replace text in a file
def find_replace(file_path, search_text, replace_text):
    with open(file_path, 'r') as f:
        text = f.read()
        modified_text = text.replace(search_text, replace_text)
    with open(file_path, 'w') as f:
        f.write(modified_text)
# Python script to generate random text
import random, string

def generate_random_text(length):
    letters = string.ascii_letters + string.digits + string.punctuation
    random_text = ''.join(random.choice(letters) for i in range(length))
    return random_text

4. Email Automation

Scripts for sending personalized emails, attaching files, and scheduling reminder emails.

# Python script to send personalized emails to a list of recipients
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_personalized_email(sender_email, sender_password, recipients, subject, body):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender_email, sender_password)
    for recipient_email in recipients:
        message = MIMEMultipart()
        message['From'] = sender_email
        message['To'] = recipient_email
        message['Subject'] = subject
        message.attach(MIMEText(body, 'plain'))
        server.sendmail(sender_email, recipient_email, message.as_string())
    server.quit()
# Python script to send emails with file attachments
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

def send_email_with_attachment(sender_email, sender_password, recipient_email, subject, body, file_path):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender_email, sender_password)
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = recipient_email
    message['Subject'] = subject
    message.attach(MIMEText(body, 'plain'))
    with open(file_path, "rb") as attachment:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', f'attachment; filename={file_path}')
        message.attach(part)
    server.sendmail(sender_email, recipient_email, message.as_string())
    server.quit()
# Python script to send automatic email reminders
import smtplib
from email.mime.text import MIMEText
from datetime import datetime

def send_reminder_email(sender_email, sender_password, recipient_email, subject, body, reminder_date):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender_email, sender_password)
    now = datetime.now()
    reminder_date = datetime.strptime(reminder_date, '%Y-%m-%d')
    if now.date() == reminder_date.date():
        message = MIMEText(body, 'plain')
        message['From'] = sender_email
        message['To'] = recipient_email
        message['Subject'] = subject
        server.sendmail(sender_email, recipient_email, message.as_string())
    server.quit()

5. Excel Automation

Reading/writing Excel files, data analysis, and merging multiple sheets.

# Python script to read and write data to an Excel spreadsheet
import pandas as pd

def read_excel(file_path):
    df = pd.read_excel(file_path)
    return df

def write_to_excel(data, file_path):
    df = pd.DataFrame(data)
    df.to_excel(file_path, index=False)
# Python script for data analysis and visualization with pandas and matplotlib
import pandas as pd
import matplotlib.pyplot as plt

def analyze_and_visualize_data(data):
    # Your code here for data analysis and visualization
    pass
# Python script to merge multiple Excel sheets into a single sheet
import pandas as pd

def merge_sheets(file_path, output_file_path):
    xls = pd.ExcelFile(file_path)
    df = pd.DataFrame()
    for sheet_name in xls.sheet_names:
        sheet_df = pd.read_excel(xls, sheet_name)
        df = df.append(sheet_df)
    df.to_excel(output_file_path, index=False)

6. Database Interaction

Connecting to SQLite, executing queries, and backing up/restoring databases.

# Python script to connect to a database and execute queries
import sqlite3

def connect_to_database(database_path):
    connection = sqlite3.connect(database_path)
    return connection

def execute_query(connection, query):
    cursor = connection.cursor()
    cursor.execute(query)
    result = cursor.fetchall()
    return result
# Python script for database backup and restore
import shutil

def backup_database(database_path, backup_directory):
    shutil.copy(database_path, backup_directory)

def restore_database(backup_path, database_directory):
    shutil.copy(backup_path, database_directory)

7. Social Media Automation

Posting to Twitter and Facebook, sharing random content, and scraping social media data.

# Python script to automate posting on Twitter and Facebook
from twython import Twython
import facebook

def post_to_twitter(api_key, api_secret, access_token, access_token_secret, message):
    twitter = Twython(api_key, api_secret, access_token, access_token_secret)
    twitter.update_status(status=message)

def post_to_facebook(api_key, api_secret, access_token, message):
    graph = facebook.GraphAPI(access_token)
    graph.put_object(parent_object='me', connection_name='feed', message=message)
# Python script for scraping data from social media platforms
import requests

def scrape_social_media_data(url):
    response = requests.get(url)
    # Your code here to extract relevant data from the response

8. System Task Automation

Managing processes, scheduling tasks with cron syntax, and monitoring disk space.

# Python script to manage system processes
import psutil

def get_running_processes():
    return [p.info for p in psutil.process_iter(['pid', 'name', 'username'])]

def kill_process_by_name(process_name):
    for p in psutil.process_iter(['pid', 'name', 'username']):
        if p.info['name'] == process_name:
            p.kill()
# Python script to schedule tasks using cron syntax
from crontab import CronTab

def schedule_task(command, schedule):
    cron = CronTab(user=True)
    job = cron.new(command=command)
    job.setall(schedule)
    cron.write()
# Python script to monitor disk space and send an alert if low
import psutil

def check_disk_space(minimum_threshold_gb):
    disk = psutil.disk_usage('/')
    free_space_gb = disk.free / (1024 ** 3)
    if free_space_gb < minimum_threshold_gb:
        # Your code here to send an alert (email, notification, etc.)
        pass

9. Image Automation

Resizing, cropping, adding watermarks, and creating thumbnails.

# Python script to resize and crop images
from PIL import Image

def resize_image(input_path, output_path, width, height):
    image = Image.open(input_path)
    resized_image = image.resize((width, height), Image.ANTIALIAS)
    resized_image.save(output_path)

def crop_image(input_path, output_path, left, top, right, bottom):
    image = Image.open(input_path)
    cropped_image = image.crop((left, top, right, bottom))
    cropped_image.save(output_path)
# Python script to add watermarks to images
from PIL import Image, ImageDraw, ImageFont

def add_watermark(input_path, output_path, watermark_text):
    image = Image.open(input_path)
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype('arial.ttf', 36)
    draw.text((10, 10), watermark_text, fill=(255, 255, 255, 128), font=font)
    image.save(output_path)
# Python script to create image thumbnails
from PIL import Image

def create_thumbnail(input_path, output_path, size=(128, 128)):
    image = Image.open(input_path)
    image.thumbnail(size)
    image.save(output_path)

The article concludes by summarizing that these nine Python scripts can greatly improve work automation across diverse tasks.

PythonAutomationDatabasescriptingWeb ScrapingEmailSystem Tasks
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.