Python 15個日常提效的自動化腳本
1. 自動備份文件夾
import shutil
import datetime
def backup_files(source, destination):
timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
backup_folder = f"{destination}/{timestamp}"
shutil.copytree(source, backup_folder)
print(f"已備份至: {backup_folder}")
# 示例用法
source_folder = "/path/to/source"
destination_folder = "/path/to/destination"
backup_files(source_folder, destination_folder)
2. 發(fā)送郵件提醒
import smtplib
from email.mime.text import MIMEText
def send_email(subject, body, to):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = "your_email@example.com"
msg['To'] = to
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login("your_email@example.com", "your_password")
server.send_message(msg)
# 示例用法
send_email("任務提醒", "別忘了今天的會議!", "receiver@example.com")
3. 自動下載網(wǎng)頁內容
import requests
def download_web_content(url, filename):
response = requests.get(url)
if response.status_code == 200:
with open(filename, 'w', encoding='utf-8') as file:
file.write(response.text)
print(f"內容已保存至 {filename}")
else:
print("請求失敗,狀態(tài)碼:", response.status_code)
# 示例用法
url = "https://news.example.com/article"
download_web_content(url, "article.txt")
4. 簡易密碼管理器
import json
def save_credentials(site, username, password, filename="passwords.json"):
data = {site: {"username": username, "password": password}}
with open(filename, 'a+') as file:
file.seek(0)
try:
existing_data = json.load(file)
existing_data.update(data)
file.seek(0)
json.dump(existing_data, file, indent=4)
except json.JSONDecodeError:
json.dump(data, file, indent=4)
def retrieve_credentials(site, filename="passwords.json"):
with open(filename, 'r') as file:
data = json.load(file)
return data.get(site, None)
# 示例用法
save_credentials("example.com", "user1", "pass123")
print(retrieve_credentials("example.com"))
5. 圖片下載器
import os
import requests
def download_images(urls, folder="images"):
if not os.path.exists(folder):
os.makedirs(folder)
for url in urls:
response = requests.get(url)
if response.status_code == 200:
filename = os.path.join(folder, url.split("/")[-1])
with open(filename, 'wb') as f:
f.write(response.content)
6. 自動化Excel數(shù)據(jù)處理
import pandas as pd
def process_excel(file_path):
# 讀取Excel文件
df = pd.read_excel(file_path)
# 數(shù)據(jù)清洗示例:去除空值行
df.dropna(inplace=True)
# 將處理后的數(shù)據(jù)保存回Excel
output_file_path = file_path.replace('.xlsx', '_processed.xlsx')
df.to_excel(output_file_path, index=False)
print(f"已處理并保存至: {output_file_path}")
# 示例用法
process_excel("/path/to/excel/file.xlsx")
7. 網(wǎng)絡速度測試
首先需要安裝speedtest-cli庫:
pip install speedtest-cli
然后編寫腳本如下:
import speedtest
def test_network_speed():
st = speedtest.Speedtest()
download_speed = st.download() / 10**6 # Mbps
upload_speed = st.upload() / 10**6 # Mbps
print(f"下載速度: {download_speed:.2f} Mbps")
print(f"上傳速度: {upload_speed:.2f} Mbps")
# 示例用法
test_network_speed()
8. 自動化社交媒體帖子發(fā)布
這通常需要API密鑰和相應的API文檔來實現(xiàn)。以Twitter為例,您需要使用Tweepy庫,并設置API訪問權限。
首先確保你已經安裝了tweepy庫:
pip install tweepy
然后創(chuàng)建一個Python腳本來發(fā)布推文:
import tweepy
# 填寫你的Twitter開發(fā)者賬號提供的API密鑰
API_KEY = 'your_api_key'
API_SECRET_KEY = 'your_api_secret_key'
ACCESS_TOKEN = 'your_access_token'
ACCESS_TOKEN_SECRET = 'your_access_token_secret'
def post_tweet(tweet_text):
# 設置認證信息
auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
# 創(chuàng)建API對象
api = tweepy.API(auth)
try:
# 發(fā)布推文
api.update_status(tweet_text)
print("推文已成功發(fā)布!")
except Exception as e:
print(f"發(fā)布推文時出錯: {e}")
# 示例用法
post_tweet("這是通過Python自動發(fā)布的測試推文!")
請記得將your_api_key, your_api_secret_key, your_access_token, 和 your_access_token_secret替換為你從Twitter開發(fā)者賬戶獲取的實際值。
9. 電腦定時關機
在Windows系統(tǒng)中可以這樣操作:
import os
import time
def schedule_shutdown(minutes):
seconds = minutes * 60
time.sleep(seconds)
os.system("shutdown -s -t 0") # Windows命令
# 示例用法
schedule_shutdown(30) # 計劃30分鐘后關機
10. 監(jiān)控CPU使用率
使用psutil庫來監(jiān)控CPU使用情況:
import psutil
def monitor_cpu_usage(interval=1):
while True:
cpu_percent = psutil.cpu_percent(interval=interval)
print(f"當前CPU使用率: {cpu_percent}%")
# 示例用法
monitor_cpu_usage()
11. 解析和提取HTML
from bs4 import BeautifulSoup
import requests
def scrape_data(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取所需數(shù)據(jù)...
12. 批量重命名文件
import os
def batch_rename_files(directory, prefix):
for idx, filename in enumerate(os.listdir(directory)):
ext = os.path.splitext(filename)[1]
new_name = f"{prefix}_{idx+1}{ext}"
os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
print(f"重命名為: {new_name}")
# 示例用法
batch_rename_files("/path/to/directory", "new_filename")
13. 清理重復文件
清理重復文件通常涉及計算每個文件的哈希值(如MD5或SHA256),然后比較這些哈希值來找出重復項。下面是一個簡單的例子,它會遍歷指定目錄下的所有文件,并刪除重復的文件。
import os
import hashlib
def calculate_md5(file_path):
"""計算給定文件的MD5哈希值"""
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def remove_duplicate_files(directory):
"""在指定目錄中查找并刪除重復文件"""
file_hashes = {}
duplicates = []
for root, _, files in os.walk(directory):
for filename in files:
file_path = os.path.join(root, filename)
file_hash = calculate_md5(file_path)
if file_hash not in file_hashes:
file_hashes[file_hash] = file_path
else:
duplicates.append(file_path)
# 刪除重復文件
for duplicate in duplicates:
os.remove(duplicate)
print(f"已刪除重復文件: {duplicate}")
# 示例用法
remove_duplicate_files("/path/to/your/directory")
這段代碼首先定義了一個函數(shù)calculate_md5來計算文件的MD5哈希值,然后定義了remove_duplicate_files函數(shù)來遍歷目錄中的所有文件,并利用哈希值來識別和刪除重復文件。
14. 創(chuàng)建有聲讀物
可以使用pyttsx3庫將文本轉換為語音:
import pyttsx3
def text_to_speech(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
# 示例用法
text_to_speech("這是一個測試句子。")
15. PDF編輯器
使用PyPDF4庫進行PDF文件合并:
from PyPDF4 import PdfFileMerger
def merge_pdfs(pdf_list, output_path):
merger = PdfFileMerger()
for pdf in pdf_list:
merger.append(pdf)
merger.write(output_path)
merger.close()
print(f"合并完成并保存至: {output_path}")
# 示例用法
merge_pdfs(["file1.pdf", "file2.pdf"], "merged_output.pdf")