在快节奏的数字化时代,自动化已经成为提升效率的关键词。Python,以其简洁的语法和丰富的库支持,成为编写自动化脚本的首选语言。今天,我们将探索10个实用的Python自动化脚本,它们能够简化日常工作、提升生活品质,让你在日常任务中更加游刃有余。
1. 文件批量重命名
面对一堆杂乱无章的文件名,手动更改费时费力。以下脚本可以批量将文件名中的特定字符替换或增加前缀后缀。
import os
def batch_rename(directory, find_str, replace_str, prefix=''):
for filename in os.listdir(directory):
if find_str in filename:
new_filename = filename.replace(find_str, replace_str)
new_filename = prefix + new_filename if prefix else new_filename
os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))
# 示例用法
batch_rename('/path/to/your/directory', 'old_', 'new_', 'updated_')
2. 网页内容抓取
自动抓取网页信息,如新闻标题、天气预报等,是信息收集的有力工具。
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com/news'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for title in soup.find_all('h2', class_='news-title'):
print(title.text.strip())
3. 定时发送邮件提醒
安排会议、生日祝福或日常提醒,通过邮件自动发送。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import schedule
import time
def send_email():
sender_email = "your_email@example.com"
receiver_email = "receiver@example.com"
password = input("Type your password and press enter: ")
message = MIMEMultipart("alternative")
message["Subject"] = "Daily Reminder"
message["From"] = sender_email
message["To"] = receiver_email
text = """\
Hi,
This is your daily reminder!
"""
part = MIMEText(text, "plain")
message.attach(part)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
server.quit()
schedule.every().day.at("10:30").do(send_email)
while True:
schedule.run_pending()
time.sleep(1)
4. 数据备份脚本
定期备份重要文件,保护数据安全。
import shutil
import datetime
source_folder = '/path/to/source'
backup_folder = f'/path/to/backup/{datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}'
shutil.copytree(source_folder, backup_folder)
print(f"Backup completed at {backup_folder}")
5. 社交媒体监控
监控社交媒体上的关键词提及,例如微博、Twitter等。
import tweepy
# 需要先在Twitter开发者账户获取API密钥
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
search_query = '#Python'
tweets = api.search(q=search_query,, count=10)
for tweet in tweets:
print(tweet.user.name, tweet.text)
6. PDF文件合并
将多个PDF文件合并成一个文档。
from PyPDF2 import PdfMerger
pdf_files = ['/path/to/file1.pdf', '/path/to/file2.pdf']
merger = PdfMerger()
for pdf_file in pdf_files:
merger.append(pdf_file)
merger.write('/path/to/output.pdf')
merger.close()
print("PDFs merged successfully.")
7. 自动化表格处理
使用pandas处理CSV或Excel文件,自动化数据清洗和分析。
import pandas as pd
df = pd.read_csv('data.csv')
# 数据清洗示例:去除空值
df.dropna(inplace=True)
# 数据分析示例:计算平均值
average_score = df['Score'].mean()
print(f"Average Score: {average_score}")
8. 图片批量压缩
自动调整图片大小,节省存储空间。
from PIL import Image
def compress_image(image_path, output_path, quality=90):
img = Image.open(image_path)
img.save(output_path, optimize=True, quality=quality)
images_folder = '/path/to/images'
for filename in os.listdir(images_folder):
if filename.endswith('.jpg') or filename.endswith('.png'):
img_path = os.path.join(images_folder, filename)
output_path = os.path.join(images_folder, f"compressed_{filename}")
compress_image(img_path, output_path)
print("Images compressed.")
9. 网络状态监测
定期检查网络连接状况,确保在线服务稳定。
import urllib.request
import time
def check_internet():
try:
urllib.request.urlopen("http://www.google.com", timeout=5)
print("Internet is connected.")
except urllib.error.URLError:
print("No internet connection.")
while True:
check_internet()
time.sleep(60) # 每分钟检查一次
10. 系统资源监控
监控CPU和内存使用情况,预防系统过载。
import psutil
def monitor_resources():
cpu_percent = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
print(f"CPU Usage: {cpu_percent}%")
print(f"Memory Usage: {memory_info.percent}%")
while True:
monitor_resources()
time.sleep(5) # 每5秒检查一次
总结
以上脚本涵盖了日常办公、数据分析、系统维护等多个领域的自动化需求,展现了Python在提升工作效率和生活质量方面的巨大潜力。希望这些建议能够激发你的灵感,让你的日常生活更加智能化和高效。实践是检验真理的唯一标准,不妨从现在开始,根据自己的需求定制专属的自动化解决方案吧!