Operations 20 min read

9 Practical Python Automation Scripts for Everyday Tasks

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

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
9 Practical Python Automation Scripts for Everyday Tasks

In this article we explore nine Python automation scenarios and provide ready‑to‑use script examples to help you complete various tasks more efficiently.

1. File Management Automation

1.1 Sort files by extension

<code># 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))
</code>

This script classifies files into sub‑folders based on their extensions.

1.2 Delete empty folders

<code># 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)
</code>

1.3 Rename multiple files

<code># 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))
</code>

2. Web Scraping with Python

2.1 Extract data from a website

<code># 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
</code>

2.2 Download images in bulk

<code># 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)
</code>

2.3 Automate form submission

<code># 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
</code>

3. Text Processing and Manipulation

3.1 Count words in a text file

<code># 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
</code>

3.2 Find and replace text in a file

<code># 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)
</code>

3.3 Generate random text

<code># Python script to generate random text
import random
import 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
</code>

4. Email Automation

4.1 Send personalized emails

<code># 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()
</code>

4.2 Send emails with attachments

<code># 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()
</code>

4.3 Automatic email reminders

<code># 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()
</code>

5. Excel Automation

5.1 Read & write Excel files

<code># 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)
</code>

5.2 Data analysis and visualization

<code># 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
</code>

5.3 Merge multiple sheets into one

<code># 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)
</code>

6. Database Interaction

6.1 Connect to a database

<code># 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
</code>

6.2 Execute SQL queries (same function shown above)

6.3 Backup and restore databases

<code>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)
</code>

7. Social Media Automation

7.1 Post to Twitter and Facebook

<code># 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)
</code>

7.2 Share random content automatically

<code># Python script to automatically share random content on social media platforms
import random

def get_random_content():
  # Your code here to retrieve random content from a list or database
  pass

def post_random_content_to_twitter(api_key, api_secret, access_token, access_token_secret):
  content = get_random_content()
  post_to_twitter(api_key, api_secret, access_token, access_token_secret, content)

def post_random_content_to_facebook(api_key, api_secret, access_token):
  content = get_random_content()
  post_to_facebook(api_key, api_secret, access_token, content)
</code>

7.3 Scrape social media data

<code># 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
</code>

8. System Task Automation

8.1 Manage system processes

<code># 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()
</code>

8.2 Schedule tasks with cron syntax

<code># 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()
</code>

8.3 Monitor disk space and alert

<code># Python script to monitor disk space and send an alert if it's 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
</code>

9. Image Editing Automation

9.1 Resize and crop images

<code># 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)
</code>

9.2 Add watermarks to images

<code># 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)
</code>

9.3 Create image thumbnails

<code># 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)
</code>

These nine Python scripts demonstrate how to automate common tasks across file handling, web interaction, text processing, email communication, data analysis, system administration, and image manipulation, providing a solid foundation for building more complex automation workflows.

PythonAutomationimage processingDatabasescriptingWeb Scrapingfile managementEmail
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.