Fundamentals 9 min read

10 Useful Python Scripts to Automate Everyday Tasks

This article presents ten practical Python scripts—including data analysis with Pandas, web scraping with BeautifulSoup, file renaming, image resizing, PDF generation, email sending, data backup, password generation, a simple HTTP server, and SQLite backup/restore—to help automate common programming tasks.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
10 Useful Python Scripts to Automate Everyday Tasks

Python is a versatile programming language widely used for web development, data analysis, and automation. This article presents ten practical Python scripts that automate common tasks.

1. Data analysis with Pandas

Pandas provides powerful data manipulation; the example reads a CSV file, computes the mean of a column, and prints the result.

import pandas as pd

# Read data from a CSV file
data = pd.read_csv('data.csv')

# Perform basic analysis
mean = data['column_name'].mean()
print(f"Mean: {mean}")

2. Web scraping with BeautifulSoup

BeautifulSoup simplifies extracting information from web pages. The script fetches a page, parses the HTML, and prints the text of a specific div element.

import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Extract data from the webpage
data = soup.find('div', class_='content')
print(data.text)

3. Batch file renaming

This script iterates over files in a folder and renames those that start with a given prefix.

import os

folder_path = '/path/to/folder'
for filename in os.listdir(folder_path):
    if filename.startswith('prefix_'):
        new_filename = filename.replace('prefix_', 'new_prefix_')
        os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))

4. Image resizing with Pillow

Pillow enables easy image processing; the script resizes all images in a directory to a specified size while preserving aspect ratio.

from PIL import Image
import os

input_folder = '/path/to/images'
output_folder = '/path/to/resized_images'
desired_size = (100, 100)

for filename in os.listdir(input_folder):
    with Image.open(os.path.join(input_folder, filename)) as img:
        img.thumbnail(desired_size)
        img.save(os.path.join(output_folder, filename))

5. PDF generation with ReportLab

ReportLab creates PDF documents programmatically. The example writes a simple text string onto a new PDF file.

from reportlab.pdfgen import canvas

pdf_file = 'output.pdf'
text = 'Hello, this is a sample PDF.'

c = canvas.Canvas(pdf_file)
c.drawString(100, 750, text)
c.save()

6. Automated email sending with smtplib

The script composes and sends an email using SMTP, demonstrating how to attach plain‑text content.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

smtp_server = 'smtp.example.com'
sender_email = '[email protected]'
receiver_email = '[email protected]'
password = 'your_password'

message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'Sample Email Subject'

body = 'This is a sample email message.'
message.attach(MIMEText(body, 'plain'))

with smtplib.SMTP(smtp_server, 587) as server:
    server.starttls()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())

7. Simple data backup script

Using shutil , this script copies a source folder to a backup location.

import shutil

source_folder = '/path/to/source_folder'
backup_folder = '/path/to/backup_folder'

shutil.copytree(source_folder, backup_folder)

8. Random password generator

The script creates a strong random password composed of letters, digits, and punctuation.

import random
import string

def generate_password(length=12):
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(characters) for _ in range(length))

password = generate_password()
print(password)

9. Simple HTTP server

A minimal HTTP server for testing and development, listening on port 8000.

import http.server
import socketserver

port = 8000

with socketserver.TCPServer(('', port), http.server.SimpleHTTPRequestHandler) as httpd:
    print(f"Serving at port {port}")
    httpd.serve_forever()

10. SQLite database backup and restore

This script demonstrates how to copy an SQLite database file for backup and how to restore it, offering a simple command‑line menu.

import sqlite3
import shutil

# Database file paths
source_db_file = 'source.db'
backup_db_file = 'backup.db'

# Function to create a backup of the SQLite database
def backup_database():
    try:
        shutil.copy2(source_db_file, backup_db_file)
        print("Backup successful.")
    except Exception as e:
        print(f"Backup failed: {str(e)}")

# Function to restore the SQLite database from a backup
def restore_database():
    try:
        shutil.copy2(backup_db_file, source_db_file)
        print("Restore successful.")
    except Exception as e:
        print(f"Restore failed: {str(e)}")

# Simple menu
while True:
    print("Options:")
    print("1. Backup Database")
    print("2. Restore Database")
    print("3. Quit")
    choice = input("Enter your choice (1/2/3): ")

    if choice == '1':
        backup_database()
    elif choice == '2':
        restore_database()
    elif choice == '3':
        break
    else:
        print("Invalid choice. Please enter 1, 2, or 3.")

These scripts illustrate how Python can be leveraged to streamline routine tasks across data processing, web interaction, file management, document creation, communication, and database maintenance.

AutomationSQLiteWeb ScrapingpandasEmailScripts
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.