17 Practical Python Scripts for Automating Everyday Tasks
This article presents 17 versatile Python scripts that automate common tasks such as file management, web scraping, email handling, Excel processing, database interaction, system administration, and more, offering code examples and explanations to help developers and analysts improve productivity.
Python is a popular language for automating repetitive tasks. The article introduces 17 useful scripts covering file management, web scraping, text processing, email automation, Excel handling, database operations, system tasks, image processing, network automation, data cleaning, PDF manipulation, GUI automation, testing, cloud services, finance, and natural‑language processing.
1. File Management
Sort files by extension:
# 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))Remove empty folders:
# 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)2. Web Scraping
Extract data from a website using requests and BeautifulSoup :
# 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 website3. Email Automation
Send personalized emails:
# 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()4. Excel Automation
Read and write Excel files with pandas :
# 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)5. Database Interaction
Connect to SQLite and execute queries:
# 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 result6. System Task Automation
Manage system processes with psutil :
# 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()7. Image Automation
Resize and crop images using Pillow:
# 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)8. Network Automation
Check website status:
# 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
pass9. Data Cleaning & Transformation
Remove duplicates with pandas:
# Python script to remove duplicates from data
import pandas as pd
def remove_duplicates(data_frame):
cleaned_data = data_frame.drop_duplicates()
return cleaned_data10. PDF Automation
Extract text from PDFs using PyPDF2:
# 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 text11. GUI Automation
Automate GUI actions with pyautogui :
# Python script for GUI automation using pyautogui
import pyautogui
def automate_gui():
# Your code here for GUI automation using pyautogui
pass12. Testing Automation
Unit testing with unittest :
# 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()13. Cloud Service Automation
Create an EC2 instance with Boto3:
# 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].id14. Financial Automation
Fetch currency exchange rates (placeholder for API calls):
# Python script to fetch currency exchange rates
# Your code here to connect to a currency exchange API (e.g., Fixer.io, Open Exchange Rates)15. Natural Language Processing
Sentiment analysis with NLTK:
# 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_scoreThe article concludes by encouraging readers to start using these scripts to streamline workflows, save time, and increase 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.