Fundamentals 8 min read

10 Practical Python Automation Scripts to Boost Productivity

Discover ten useful Python automation scripts—including batch file renaming, web scraping, scheduled email alerts, data backup, social media monitoring, PDF merging, spreadsheet processing, image compression, network checks, and system resource monitoring—that simplify everyday tasks and enhance efficiency.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
10 Practical Python Automation Scripts to Boost Productivity

In the fast‑paced digital era, automation is a key driver of efficiency, and Python’s concise syntax and extensive libraries make it an ideal language for writing automation scripts.

1. Batch File Renaming

This script batch‑renames files by replacing a target substring and optionally adding a prefix or suffix.

import os

def batch_rename(directory, find_str, replace_str, prefix=''):
    for filename in os.listdir(directory):
        if find_str in filename:
            new_filename = filename.replace(find_str, replace_str)
            new_filename = prefix + new_filename if prefix else new_filename
            os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))

# Example usage
batch_rename('/path/to/your/directory', 'old_', 'new_', 'updated_')

2. Web Content Scraping

Automatically fetch web information such as news headlines or weather forecasts.

import requests
from bs4 import BeautifulSoup

url = 'https://www.example.com/news'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for title in soup.find_all('h2', class_='news-title'):
    print(title.text.strip())

3. Scheduled Email Reminders

Send automated email reminders for meetings, birthdays, or daily notifications.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import schedule, time

def send_email():
    sender_email = "[email protected]"
    receiver_email = "[email protected]"
    password = input("Type your password and press enter: ")
    message = MIMEMultipart("alternative")
    message["Subject"] = "Daily Reminder"
    message["From"] = sender_email
    message["To"] = receiver_email
    text = """\
Hi,
This is your daily reminder!
"""
    part = MIMEText(text, "plain")
    message.attach(part)
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())
    server.quit()

schedule.every().day.at("10:30").do(send_email)
while True:
    schedule.run_pending()
    time.sleep(1)

4. Data Backup Script

Periodically back up important files to protect data safety.

import shutil, datetime

source_folder = '/path/to/source'
backup_folder = f"/path/to/backup/{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}"
shutil.copytree(source_folder, backup_folder)
print(f"Backup completed at {backup_folder}")

5. Social Media Monitoring

Monitor keyword mentions on platforms such as Twitter.

import tweepy
# Obtain API keys from Twitter developer portal
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
search_query = '#Python'
tweets = api.search(q=search_query, count=10)
for tweet in tweets:
    print(tweet.user.name, tweet.text)

6. PDF File Merging

Combine multiple PDF files into a single document.

from PyPDF2 import PdfMerger

pdf_files = ['/path/to/file1.pdf', '/path/to/file2.pdf']
merger = PdfMerger()
for pdf_file in pdf_files:
    merger.append(pdf_file)
merger.write('/path/to/output.pdf')
merger.close()
print("PDFs merged successfully.")

7. Automated Spreadsheet Processing

Use pandas to handle CSV or Excel files, automating data cleaning and analysis.

import pandas as pd

df = pd.read_csv('data.csv')
# Remove empty rows
df.dropna(inplace=True)
# Calculate average score
average_score = df['Score'].mean()
print(f"Average Score: {average_score}")

8. Batch Image Compression

Resize images automatically to save storage space.

from PIL import Image
import os

def compress_image(image_path, output_path, quality=90):
    img = Image.open(image_path)
    img.save(output_path, optimize=True, quality=quality)

images_folder = '/path/to/images'
for filename in os.listdir(images_folder):
    if filename.lower().endswith(('.jpg', '.png')):
        img_path = os.path.join(images_folder, filename)
        output_path = os.path.join(images_folder, f"compressed_{filename}")
        compress_image(img_path, output_path)
print("Images compressed.")

9. Network Status Monitoring

Regularly check network connectivity to ensure online services remain stable.

import urllib.request, time

def check_internet():
    try:
        urllib.request.urlopen('http://www.google.com', timeout=5)
        print('Internet is connected.')
    except urllib.error.URLError:
        print('No internet connection.')

while True:
    check_internet()
    time.sleep(60)  # check every minute

10. System Resource Monitoring

Monitor CPU and memory usage to prevent system overload.

import psutil, time

def monitor_resources():
    cpu_percent = psutil.cpu_percent(interval=1)
    memory_info = psutil.virtual_memory()
    print(f"CPU Usage: {cpu_percent}%")
    print(f"Memory Usage: {memory_info.percent}%")

while True:
    monitor_resources()
    time.sleep(5)  # check every 5 seconds

These scripts cover a wide range of automation needs—from everyday office tasks and data analysis to system maintenance—showcasing Python’s powerful capability to boost productivity and improve quality of life. Feel free to adapt and extend them to suit your own workflows.

productivityscriptingDataProcessing
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

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.