Python 的九個自動化實戰(zhàn)腳本示例
在這個快節(jié)奏的時代,Python以其簡潔的語法和強大的庫支持,成為了自動化日常任務(wù)的首選工具。想象一下,無需手動重復(fù)點擊,幾行代碼就能完成文件管理、數(shù)據(jù)整理、網(wǎng)絡(luò)抓取等任務(wù),是不是很吸引人?接下來,我們將通過一系列簡單到高級的腳本示例,讓你的日常工作生活更加高效。
1. 自動備份文件
需求:每天自動備份指定文件夾內(nèi)的文件。
import shutil
import datetime
# 源文件夾路徑
src_folder = 'C:/Users/你的用戶名/Documents'
# 備份文件夾路徑,格式為年月日
backup_folder = f'C:/Backups/{datetime.date.today()}'
# 創(chuàng)建備份目錄
shutil.rmtree(backup_folder, ignore_errors=True) # 清除已存在的備份
os.makedirs(backup_folder, exist_ok=True)
# 復(fù)制文件
shutil.copytree(src_folder, backup_folder)
print("備份完成!")
解釋:利用shutil庫進行文件和目錄操作,datetime用于生成當(dāng)前日期作為備份目錄名。
2. 郵件發(fā)送提醒
需求:定時發(fā)送郵件提醒自己或他人。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 設(shè)置郵件信息
msg = MIMEMultipart()
msg['From'] = 'your_email@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = '今日任務(wù)提醒'
body = '別忘了今天的會議哦!'
msg.attach(MIMEText(body, 'plain'))
# 發(fā)送郵件
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls() # 啟用安全傳輸
server.login('your_email@example.com', 'your_password')
text = msg.as_string()
server.sendmail(msg['From'], msg['To'], text)
server.quit()
print("郵件發(fā)送成功!")
注意:使用前需替換郵箱地址和密碼,并確保SMTP服務(wù)器設(shè)置正確。
3. 網(wǎng)頁標題抓取
需求:批量獲取網(wǎng)站列表的標題。
import requests
from bs4 import BeautifulSoup
# 網(wǎng)站列表
websites = ['https://www.example1.com', 'https://www.example2.com']
for url in websites:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.find('title').text
print(f"{url} 的標題是: {title}")
技巧:使用requests獲取網(wǎng)頁內(nèi)容,BeautifulSoup解析HTML。
這些基礎(chǔ)腳本只是冰山一角,接下來,我們將探索更高級的應(yīng)用,如數(shù)據(jù)自動化處理、社交媒體管理自動化、甚至簡單的GUI應(yīng)用,讓你的自動化技能更上一層樓。保持學(xué)習(xí),自動化之旅才剛剛開始。
4. Excel數(shù)據(jù)處理
需求:合并多個Excel文件。
import pandas as pd
# 文件所在目錄
folder_path = 'C:/ExcelFiles'
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx')]
# 合并Excel文件
frames = [pd.read_excel(os.path.join(folder_path, filename)) for filename in excel_files]
combined = pd.concat(frames, ignore_index=True)
combined.to_excel('combined.xlsx', index=False)
print("Excel文件合并完成。")
重點:使用Pandas庫簡化數(shù)據(jù)處理,pd.concat用于合并DataFrame。
5. 自動下載圖片
需求:從特定網(wǎng)站下載所有圖片。
import os
import requests
from bs4 import BeautifulSoup
url = 'http://example.com/images-page'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')
for img in img_tags:
img_url = img.get('src')
img_name = os.path.basename(img_url)
with open(img_name, 'wb') as handler:
handler.write(requests.get(img_url).content)
print(f"下載了圖片: {img_name}")
提示:確保合法下載,尊重版權(quán)。
6. 網(wǎng)絡(luò)狀態(tài)監(jiān)測
需求:監(jiān)控網(wǎng)站是否可訪問。
import time
import requests
url = 'https://www.example.com'
while True:
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
print("網(wǎng)站在線。")
else:
print("網(wǎng)站無法訪問。")
except requests.ConnectionError:
print("連接錯誤。")
time.sleep(60) # 每分鐘檢查一次
實踐:利用循環(huán)和異常處理持續(xù)監(jiān)控。
7. 任務(wù)調(diào)度:定時執(zhí)行腳本
需求:每天早上8點自動發(fā)送天氣預(yù)報郵件。 解決方案:結(jié)合Python的schedule庫和之前提到的天氣預(yù)報與郵件發(fā)送腳本。
import schedule
import time
from send_weather_email import send_weather_email # 假設(shè)這是發(fā)送天氣預(yù)報郵件的函數(shù)
def job():
send_weather_email()
schedule.every().day.at("08:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
技巧:使用schedule庫輕松安排任務(wù),確保定時準確執(zhí)行。
8. 自動化文件重命名
需求:批量重命名文件夾中的圖片,添加日期戳。
import os
import datetime
folder_path = 'C:/Pictures'
datestamp = datetime.datetime.now().strftime('%Y%m%d')
for filename in os.listdir(folder_path):
if filename.endswith('.jpg'):
new_filename = f'{datestamp}_{filename}'
src = os.path.join(folder_path, filename)
dst = os.path.join(folder_path, new_filename)
os.rename(src, dst)
print(f'Renamed: {filename} to {new_filename}')
實用提示:利用os模塊處理文件系統(tǒng)操作,增加文件管理的靈活性。
9. 簡易的個人記賬應(yīng)用
需求:記錄收支,保存到CSV文件。
import csv
def record_transaction(description, amount, type='income'):
with open('transactions.csv', mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([description, amount, type])
print("交易記錄成功。")
record_transaction("午餐", -20, "expense")
record_transaction("工資", 5000, "income")
擴展:可以進一步開發(fā)成圖形界面或數(shù)據(jù)庫存儲,提升實用性。
結(jié)語
Python的自動化能力遠不止于此。從簡單的腳本到復(fù)雜的自動化流程,Python都是你值得信賴的伙伴。