17 Practical Python Scripts for Automating Common Tasks
This article presents seventeen versatile Python scripts that automate tasks such as file management, web scraping, email handling, database interaction, system monitoring, and image processing, providing clear code examples and explanations to help developers and analysts streamline workflows and boost productivity.
This article introduces a collection of seventeen useful Python scripts designed to automate repetitive and time‑consuming tasks across various domains, offering ready‑to‑run code examples and brief explanations for each use case.
1. File Management Automation
1.1 Sort files by extension
import os
from shutil import move
def sort_files(directory_path):
for filename in os.listdir(directory_path):
if os.path.path.isfile(os.path.join(directory_path, filename)):
file_extension = filename.split('.')[-1]
destination_directory = os.path.path.join(directory_path, file_extension)
if not os.path.path.exists(destination_directory):
os.makedirs(destination_directory)
move(os.path.path.join(directory_path, filename), os.path.path.join(destination_directory, filename))This script groups files into sub‑folders based on their extensions.
1.2 Delete empty folders
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.path.join(root, folder)
if not os.listdir(folder_path):
os.rmdir(folder_path)It recursively removes any empty directories.
1.3 Batch rename files
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.path.join(directory_path, filename), os.path.path.join(directory_path, new_filename))Allows bulk renaming based on a pattern.
2. Web Scraping
2.1 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')
# add extraction logic hereUses requests and BeautifulSoup to fetch and parse HTML.
2.2 Batch download images
import requests
def download_images(url, save_directory):
response = requests.get(url)
if response.status_code == 200:
images = response.json() # assume API returns a list 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)Downloads a list of images returned by an API.
2.3 Automatic form submission
import requests
def submit_form(url, form_data):
response = requests.post(url, data=form_data)
if response.status_code == 200:
# handle response
passSends a POST request with form data.
3. Text Processing
3.1 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_countReturns the number of words in the given file.
3.2 Find and replace text
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)Performs a global search‑and‑replace.
3.3 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_textCreates a random string useful for testing.
4. Email Automation
4.1 Send personalized emails
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()Sends customized messages to a list of recipients.
4.2 Email with attachment
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()Allows sending files together with the email body.
4.3 Automated reminder email
import smtplib
from email.mime.text import MIMEText
from datetime import datetime, timedelta
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()Sends a reminder on a specific date.
5. Excel Automation
5.1 Read & write Excel
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)Uses pandas for simple spreadsheet I/O.
5.2 Data analysis & visualization (placeholder)
import pandas as pd
import matplotlib.pyplot as plt
def analyze_and_visualize_data(data):
# add analysis and plotting code here
passSkeleton for further analysis.
5.3 Merge multiple sheets
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=sheet_name)
df = df.append(sheet_df)
df.to_excel(output_file_path, index=False)Combines all worksheets into one.
6. Database Interaction
6.1 Connect to SQLite
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 resultProvides a simple wrapper for SQLite operations.
6.2 Backup & 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)Copies the database file for safety.
7. Social Media Automation
7.1 Post to 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)Publishes a status update on both platforms.
7.2 Random content sharing (placeholder)
import random
def get_random_content():
# retrieve random content from a list or DB
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)Shares randomly selected posts.
7.3 Scrape social media data (placeholder)
import requests
def scrape_social_media_data(url):
response = requests.get(url)
# extract relevant data from response
passTemplate for extracting data from social platforms.
8. System Task Automation
8.1 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()Lists processes and can terminate a specific one.
8.2 Schedule tasks with cron
from crontab import CronTab
def schedule_task(command, schedule):
cron = CronTab(user=True)
job = cron.new(command=command)
job.setall(schedule)
cron.write()Creates a cron job using the crontab library.
8.3 Monitor disk space
import psutil
def check_disk_space(minimum_threshold_gb):
disk = psutil.disk_usage('/')
free_space_gb = disk.free / (2**30)
if free_space_gb < minimum_threshold_gb:
# add alert logic here
passAlerts when free space falls below a threshold.
9. Image Automation
9.1 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)Uses Pillow to manipulate image dimensions.
9.2 Add watermark
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)Overlays semi‑transparent text on an image.
9.3 Create thumbnail
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)Generates a smaller preview version of an image.
Conclusion
The nine sections above demonstrate how Python can be leveraged to automate file handling, web interactions, email workflows, database operations, system monitoring, and image processing, enabling developers to save time, reduce errors, and increase overall productivity.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.