Today, we will discuss 10 practical Python automation scripts that can help simplify your daily work and boost your efficiency. Whether it's dealing with Excel files, sending emails, or automating web operations, Python has got you covered.
1. Batch Rename Files
If you need to rename a batch of files, such as adding prefixes or suffixes, you can use the following script:
import os
def batch_rename_files(directory, prefix):
"""Batch rename all files in the specified directory, adding a prefix"""
for filename in os.listdir(directory):
new_name = f"{prefix}_{filename}"
os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
print("Files renamed successfully")
# Example usage
batch_rename_files('path/to/your/directory', 'new_prefix')Explanation: This script iterates through all files in a specified directory and adds the given prefix to each file.
2. Auto-send Emails
Using the smtplib library, you can easily automate sending emails.
import smtplib
from email.mime.text import MIMEText
def send_email(subject, body, to_email):
"""Send an email"""
from_email = 'your_email@example.com'
password = 'your_email_password'
# Create the email content
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
# Send the email
with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
server.login(from_email, password)
server.send_message(msg)
print("Email sent successfully")
# Example usage
send_email("Test Subject", "This is a test email", "recipient@example.com")Explanation: Make sure to replace the email address and SMTP server information to match your email settings.
3. Batch Process Excel Files
Using the pandas and openpyxl libraries, you can easily read and write Excel files.
import pandas as pd
def process_excel(file_path):
"""Read Excel file and process the data"""
df = pd.read_excel(file_path) # Read Excel file
df['New Column'] = df['Original Column'] * 2 # Add a new column in DataFrame
df.to_excel('processed_file.xlsx', index=False) # Save the processed results
print("Excel file processed successfully")
# Example usage
process_excel('path/to/your/excel_file.xlsx')Explanation: This script reads a specified Excel file, performs a simple mathematical operation on one of the columns, and then saves the processed data to a new Excel file.
4. Web Scraping Data
Using the requests and BeautifulSoup libraries, you can easily scrape data from websites.
import requests
from bs4 import BeautifulSoup
def fetch_data(url):
"""Scrape data from the specified URL"""
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
titles = [title.get_text() for title in soup.find_all('h2')] # Assuming titles are in <h2> tags
print("Scraped titles:")
for title in titles:
print(title)
# Example usage
fetch_data('https://example.com')Explanation: This script visits a specified URL, parses the HTML content, and extracts the text from all <h2> tags.
5. File Backup
This script helps you quickly back up files from a specified directory.
import shutil
import os
import datetime
def backup_files(source_directory, backup_directory):
"""Back up files to the specified directory"""
date_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = os.path.join(backup_directory, f"backup_{date_str}")
shutil.copytree(source_directory, backup_path) # Copy entire directory
print(f"Backup completed: {backup_path}")
# Example usage
backup_files('path/to/source_directory', 'path/to/backup_directory')Explanation: This script uses shutil.copytree() to copy all files from the source directory to the backup directory.
6. Auto-generate Reports
If you need to generate reports based on data, you can use pandas to process the data and generate reports in PDF or Excel format.
import pandas as pd
def generate_report(data):
"""Generate a simple Excel report from data"""
df = pd.DataFrame(data)
df.to_excel('report.xlsx', index=False)
print("Report generated: report.xlsx")
# Example usage
data = {
'Name': ['Zhang San', 'Li Si'],
'Score': [90, 85]
}
generate_report(data)Explanation: This script converts sample data into an Excel file.
7. Batch Image Processing
Using the Pillow library, you can batch process images, such as resizing or converting formats.
from PIL import Image
import os
def resize_images(source_directory, output_directory, size=(800, 800)):
"""Resize all images in the specified directory"""
if not os.path.exists(output_directory):
os.makedirs(output_directory)
for filename in os.listdir(source_directory):
if filename.endswith(('.png', '.jpg', '.jpeg')):
img_path = os.path.join(source_directory, filename)
img = Image.open(img_path)
img = img.resize(size)
img.save(os.path.join(output_directory, filename))
print(f"Resized and saved: {filename}")
# Example usage
resize_images('path/to/source_images', 'path/to/output_images', (800, 800))Explanation: This script iterates through the specified directory, resizes each image, and saves it to the output directory.
8. Database Operations
Using the sqlite3 library, you can easily interact with SQLite databases.
import sqlite3
def create_table():
"""Create a simple SQLite table"""
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
conn.commit()
conn.close()
print("Table created successfully")
# Example usage
create_table()Explanation: This script connects to an SQLite database and creates a users table.
9. Automated Schedule Reminders
You can use the schedule library to set up scheduled tasks, such as sending reminder emails daily.
import schedule
import time
def job():
print("This is your schedule reminder! Don't forget to check your calendar.")
# Set the reminder time to 10:00 AM every day
schedule.every().day.at("10:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)Explanation: This script runs the scheduled reminder job at 10:00 AM every day.
10. Website Monitoring
You can write a simple script to monitor the status of specific websites to ensure they are running properly.
import requests
def check_website(url):
"""Check if the website is running properly"""
try:
response = requests.get(url)
if response.status_code == 200:
print(f"{url} is running normally")
else:
print(f"{url} returned status code: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Error accessing {url}: {e}")
# Example usage
check_website('https://example.com')Explanation: This script attempts to visit the specified website and checks if the response status code indicates that the site is running normally.
Conclusion
These are the top 10 Python automation scripts for office tasks. These scripts can help simplify your daily work and improve productivity. Once you master these basic skills, you will be able to handle various office tasks more efficiently.