17 Essential Python Scripts for Automating Everyday Tasks
Explore 17 practical Python scripts that automate tasks ranging from file management and web scraping to email handling, database interaction, system monitoring, and cloud services, enabling developers and analysts to boost productivity, reduce errors, and streamline workflows across diverse domains.
This article presents a comprehensive collection of 17 Python scripts designed to automate a wide variety of routine tasks, helping developers, data analysts, and IT professionals improve efficiency and reduce manual effort.
1. File Management Automation
Scripts for sorting files by extension, removing empty folders, and batch renaming files.
<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>2. Web Scraping and Data Extraction
Examples using requests and BeautifulSoup to fetch and parse web pages, as well as downloading images in bulk.
<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>3. Email Automation
Scripts for sending personalized emails, attaching files, and scheduling reminder 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. Excel and Data Analysis
Using pandas to read/write Excel files and perform basic data analysis and visualization.
<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. Database Interaction
Connecting to SQLite databases and executing queries.
<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. System Task Automation
Managing system processes, scheduling tasks with cron, and monitoring disk space.
<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>7. Image Processing Automation
Resizing, cropping, adding watermarks, and creating thumbnails with Pillow.
<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>8. Network Automation
Checking website status, automating FTP transfers, and configuring network devices.
<code># Python script to check the status of a website
import requests
def check_website_status(url):
response = requests.get(url)
if response.status_code == 200:
# Handle successful response
pass
else:
# Handle unsuccessful response
pass
</code>9. PDF Automation
Extracting text, merging PDFs, and adding password protection using PyPDF2.
<code># Python script to extract text from PDFs
import PyPDF2
def extract_text_from_pdf(file_path):
with open(file_path, 'rb') as f:
pdf_reader = PyPDF2.PdfFileReader(f)
text = ''
for page_num in range(pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
text += page.extractText()
return text
</code>10. GUI Automation
Automating mouse and keyboard actions with pyautogui and building simple GUIs with tkinter .
<code># Python script for GUI automation using pyautogui
import pyautogui
def automate_gui():
# Your code here for GUI automation using pyautogui
pass
</code>11. Testing Automation
Unit testing with unittest and web testing with Selenium .
<code># Python script for unit testing with the unittest module
import unittest
def add(a, b):
return a + b
class TestAddFunction(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
self.assertEqual(add(-2, -3), -5)
def test_add_zero(self):
self.assertEqual(add(5, 0), 5)
if __name__ == '__main__':
unittest.main()
</code>12. Cloud Service Automation
Uploading files to cloud storage and managing AWS resources with boto3 .
<code># Python script to manage AWS resources using Boto3
import boto3
def create_ec2_instance(instance_type, image_id, key_name, security_group_ids):
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
ImageId=image_id,
InstanceType=instance_type,
KeyName=key_name,
SecurityGroupIds=security_group_ids,
MinCount=1,
MaxCount=1
)
return instance[0].id
</code>13. Financial Automation
Fetching stock prices and currency exchange rates using external APIs.
<code># Python script for stock price analysis
# Your code here to fetch stock data using a financial API (e.g., Yahoo Finance)
# Your code here to analyze the data and derive insights
</code>14. Natural Language Processing
Sentiment analysis, text summarization, and language translation using NLP libraries.
<code># Python script for sentiment analysis using NLTK or other NLP libraries
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer
def analyze_sentiment(text):
nltk.download('vader_lexicon')
sia = SentimentIntensityAnalyzer()
sentiment_score = sia.polarity_scores(text)
return sentiment_score
</code>Overall, these scripts demonstrate how Python can be leveraged to automate repetitive workflows across many domains, saving time, reducing errors, and increasing 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.