17 Practical Python Scripts for Automating Common Tasks
This article presents a collection of 17 practical Python scripts that automate tasks such as file management, web scraping, email handling, Excel processing, database interaction, system administration, image editing, and more, providing code examples and explanations to help developers and analysts improve productivity through automation.
The article introduces a series of Python automation scripts aimed at reducing repetitive work for developers, data analysts, and anyone looking to streamline workflows. Each script is accompanied by a brief description and the full source code.
1. File Management
<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
<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
<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 Automation
<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
<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
<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
<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
<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. Data Cleaning & Transformation
<code># Python script to remove duplicates from data
import pandas as pd
def remove_duplicates(data_frame):
cleaned_data = data_frame.drop_duplicates()
return cleaned_data
</code>10. PDF Automation
<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>11. GUI Automation
<code># Python script for GUI automation using pyautogui
import pyautogui
def automate_gui():
# Your code here for GUI automation using pyautogui
pass
</code>12. Testing Automation
<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>13. Cloud Service Automation
<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>14. Financial Automation
<code># Python script for stock price analysis (placeholder for actual implementation)
# 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>15. Natural Language Processing
<code># Python script for sentiment analysis using NLTK
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>The article concludes by encouraging readers to start using Python for automation to save time, reduce errors, and boost overall productivity across a wide range of domains.
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.