20 Python Automation Scripts for Common Tasks
This article presents twenty practical Python scripts that automate everyday tasks such as batch file renaming, email sending, scheduling reminders, generating reports, backing up files, updating Excel sheets, downloading web pages, filling forms, extracting PDF text, converting file formats, visualizing data, and more, providing ready-to-use code examples for each.
1. Batch rename files
import os
def batch_rename(directory, new_name_prefix):
files = os.listdir(directory)
for i, filename in enumerate(files):
ext = os.path.splitext(filename)[1]
new_filename = f"{new_name_prefix}_{i+1}{ext}"
os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))
print("文件重命名完成")
# 示例调用
batch_rename('C:/example_directory', 'new_file')2. Automatic email sending
import smtplib
from email.mime.text import MIMEText
def send_email(subject, body, to_addr):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = '[email protected]'
msg['To'] = to_addr
with smtplib.SMTP('smtp.example.com') as server:
server.login('[email protected]', 'password')
server.sendmail(msg['From'], [msg['To']], msg.as_string())
print("邮件已发送")
# 示例调用
send_email('主题', '邮件内容', '[email protected]')3. Create schedule reminder
import schedule
import time
def reminder():
print("该休息了!")
schedule.every().hour.do(reminder)
while True:
schedule.run_pending()
time.sleep(1)4. Automatic report generation
import pandas as pd
def generate_report(data_path, output_path):
df = pd.read_excel(data_path)
summary = df.describe()
summary.to_excel(output_path)
print("报告生成完毕")
# 示例调用
generate_report('data.xlsx', 'report.xlsx')5. File backup
import shutil
def backup_files(src_dir, dest_dir):
shutil.copytree(src_dir, dest_dir)
print("文件备份完成")
# 示例调用
backup_files('C:/source_dir', 'D:/backup_dir')6. Automatic Excel update
import openpyxl
def update_excel(file_path, sheet_name, cell, value):
wb = openpyxl.load_workbook(file_path)
ws = wb[sheet_name]
ws[cell] = value
wb.save(file_path)
print(f"单元格 {cell} 已更新为 {value}")
# 示例调用
update_excel('data.xlsx', 'Sheet1', 'A1', 'New Value')7. Data cleaning and organization
import pandas as pd
def clean_data(file_path):
df = pd.read_excel(file_path)
df.dropna(inplace=True) # 删除缺失值
df.to_excel(file_path, index=False)
print("数据清洗完成")
# 示例调用
clean_data('data.xlsx')8. Automatic webpage download
import requests
def download_webpage(url, output_path):
response = requests.get(url)
with open(output_path, 'w', encoding='utf-8') as file:
file.write(response.text)
print("网页内容已下载")
# 示例调用
download_webpage('https://www.example.com', 'webpage.html')9. Automatic form filling
from selenium import webdriver
def fill_form(url, form_data):
driver = webdriver.Chrome()
driver.get(url)
for key, value in form_data.items():
element = driver.find_element_by_name(key)
element.send_keys(value)
submit_button = driver.find_element_by_id('submit')
submit_button.click()
print("表单已自动填写")
driver.quit()
# 示例调用
fill_form('https://example.com/form', {'name': 'John Doe', 'email': '[email protected]'})10. PDF text extraction
import PyPDF2
def extract_text_from_pdf(pdf_path):
pdfReader = PyPDF2.PdfFileReader(pdf_path)
text = ""
for page_num in range(pdfReader.numPages):
page = pdfReader.getPage(page_num)
text += page.extractText()
print(text)
# 示例调用
extract_text_from_pdf('document.pdf')11. Automatic file format conversion
import pandas as pd
def convert_file_format(input_path, output_path):
df = pd.read_excel(input_path)
df.to_csv(output_path, index=False)
print("文件格式转换完成")
# 示例调用
convert_file_format('data.xlsx', 'data.csv')12. Automatic meeting scheduling
from datetime import datetime, timedelta
import calendar
def schedule_meeting(start_time, duration_hours):
end_time = start_time + timedelta(hours=duration_hours)
print(f"会议安排在 {start_time.strftime('%Y-%m-%d %H:%M')} 至 {end_time.strftime('%Y-%m-%d %H:%M')}")
# 示例调用
schedule_meeting(datetime.now(), 2)13. Folder change monitoring
import os
import time
def monitor_folder_changes(folder_path):
before = dict([(f, None) for f in os.listdir(folder_path)])
while True:
time.sleep(1)
after = dict([(f, None) for f in os.listdir(folder_path)])
added = [f for f in after if f not in before]
removed = [f for f in before if f not in after]
if added:
print("添加了:", ", ".join(added))
if removed:
print("移除了:", ", ".join(removed))
before = after
# 示例调用
monitor_folder_changes('C:/example_folder')14. Automatic sign‑in system
from datetime import datetime
def auto_sign_in(employee_id):
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"员工 {employee_id} 在 {current_time} 签到成功")
# 示例调用
auto_sign_in(12345)15. Text analysis
from collections import Counter
import re
def analyze_text(text):
words = re.findall(r'\b\w+\b', text.lower())
word_counts = Counter(words)
print(word_counts.most_common(5))
# 示例调用
analyze_text("这是一个测试 这是一个简单的测试")16. Automated document generation
from jinja2 import Template
def generate_document(template_str, data):
template = Template(template_str)
document = template.render(data)
print(document)
# 示例调用
template = "亲爱的 {{ name }}, 您的订单编号是 {{ order_id }}."
data = {'name': '张三', 'order_id': '12345'}
generate_document(template, data)17. Data visualization
import matplotlib.pyplot as plt
import numpy as np
def plot_data(x, y):
plt.plot(x, y)
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('数据可视化')
plt.show()
# 示例调用
x = np.linspace(0, 10, 100)
y = np.sin(x)
plot_data(x, y)18. Automated financial report
import pandas as pd
def generate_financial_report(data_path, output_path):
df = pd.read_excel(data_path)
total_sales = df['销售额'].sum()
average_cost = df['成本'].mean()
report = pd.DataFrame({'总销售额': [total_sales], '平均成本': [average_cost]})
report.to_excel(output_path)
print("财务报表生成完毕")
# 示例调用
generate_financial_report('sales.xlsx', 'financial_report.xlsx')19. Automated customer feedback collection
import requests
def collect_feedback(feedback_url):
response = requests.get(feedback_url)
feedbacks = response.json()
for feedback in feedbacks:
print(f"客户ID: {feedback['customer_id']} 反馈: {feedback['comment']}")
# 示例调用
collect_feedback('https://api.example.com/feedback')20. Automated inventory management
import pandas as pd
def update_inventory(file_path, product_id, quantity_change):
df = pd.read_excel(file_path)
df.loc[df['产品ID'] == product_id, '库存数量'] += quantity_change
df.to_excel(file_path, index=False)
print("库存已更新")
# 示例调用
update_inventory('inventory.xlsx', 101, -5)Test Development Learning Exchange
Test Development Learning Exchange
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.