十個自動化日常任務(wù)的Python腳本
自動化是一種強大的方式,可以簡化日常任務(wù)并節(jié)省時間。Python憑借其簡單性和多功能性,是自動化日常生活各個方面的絕佳語言。在本文中,我們將探索10個實用的Python腳本,它們可以幫助自動化枯燥的任務(wù),提高工作效率,讓生活變得更加輕松。
1. 郵件自動化
描述:自動發(fā)送電子郵件、回復(fù)郵件或?qū)⑹盏降碾娮余]件分類到文件夾中。
腳本:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, body, to_email):
from_email = "your_email@gmail.com"
password = "your_password"
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email, password)
text = msg.as_string()
server.sendmail(from_email, to_email, text)
server.quit()
send_email("Test Subject", "This is a test email body.", "recipient_email@gmail.com")
2. 文件整理
描述:根據(jù)文件類型,將目錄中的文件整理到相應(yīng)的文件夾中。
腳本:
import os
import shutil
def organize_files(directory):
for filename in os.listdir(directory):
if os.path.isfile(os.path.join(directory, filename)):
file_type = filename.split('.')[-1]
target_dir = os.path.join(directory, file_type)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
shutil.move(os.path.join(directory, filename), os.path.join(target_dir, filename))
organize_files('/path/to/your/directory')
3. 每日新聞網(wǎng)頁抓取
描述:從網(wǎng)站上抓取最新的新聞標(biāo)題,并將其保存到文本文件中。
腳本:
import requests
from bs4 import BeautifulSoup
def scrape_news(url, output_file):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
headlines = soup.find_all('h2', class_='title')
with open(output_file, 'w') as file:
for headline in headlines:
file.write(headline.text.strip() + '\n')
scrape_news('https://www.example-news-website.com', 'daily_news.txt')
4. 數(shù)據(jù)備份自動化
描述:將重要文件和目錄備份到云存儲服務(wù),如Dropbox。
腳本:
import dropbox
import os
def backup_files(local_directory, dropbox_access_token, dropbox_directory):
dbx = dropbox.Dropbox(dropbox_access_token)
for root, dirs, files in os.walk(local_directory):
for filename in files:
local_path = os.path.join(root, filename)
relative_path = os.path.relpath(local_path, local_directory)
dropbox_path = os.path.join(dropbox_directory, relative_path)
with open(local_path, 'rb') as f:
dbx.files_upload(f.read(), dropbox_path, mode=dropbox.files.WriteMode.overwrite)
backup_files('/path/to/local/directory', 'your_dropbox_access_token', '/backup_directory')
5. 社交媒體自動化
描述:將更新發(fā)布到社交媒體平臺,如Twitter。
腳本:
import tweepy
def post_tweet(api_key, api_key_secret, access_token, access_token_secret, message):
auth = tweepy.OAuth1UserHandler(api_key, api_key_secret, access_token, access_token_secret)
api = tweepy.API(auth)
api.update_status(message)
post_tweet('api_key', 'api_key_secret', 'access_token', 'access_token_secret', 'Hello, Twitter!')
6. 日歷事件創(chuàng)建器
描述:自動在Google日歷中創(chuàng)建事件。
腳本:
from google.oauth2 import service_account
from googleapiclient.discovery import build
def create_event(calendar_id, summary, start_time, end_time):
SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = 'path/to/credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('calendar', 'v3', credentials=credentials)
event = {
'summary': summary,
'start': {'dateTime': start_time, 'timeZone': 'UTC'},
'end': {'dateTime': end_time, 'timeZone': 'UTC'}
}
event = service.events().insert(calendarId=calendar_id, body=event).execute()
print(f'Event created: {event.get("htmlLink")}')
create_event('your_calendar_id', 'Meeting', '2022-07-01T10:00:00Z', '2022-07-01T11:00:00Z')
7. 天氣預(yù)報通知
描述:獲取每日天氣預(yù)報,并以電子郵件形式發(fā)送通知。
腳本:
import requests
import smtplib
from email.mime.text import MIMEText
def send_weather_forecast(api_key, city, email):
weather_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(weather_url)
weather_data = response.json()
weather_description = weather_data['weather'][0]['description']
temperature = weather_data['main']['temp'] - 273.15 # Convert Kelvin to Celsius
message = f"Today's weather in {city}:\n{weather_description}\nTemperature: {temperature:.2f}°C"
msg = MIMEText(message)
msg['Subject'] = f"Weather Forecast for {city}"
msg['From'] = "your_email@gmail.com"
msg['To'] = email
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login("your_email@gmail.com", "your_password")
server.send_message(msg)
send_weather_forecast('your_openweathermap_api_key', 'London', 'recipient_email@gmail.com')
8. 自動化財務(wù)交易
描述:自動管理和記錄財務(wù)交易。
腳本:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
def record_transaction(spreadsheet_id, transaction_data):
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_name('path/to/credentials.json', scope)
client = gspread.authorize(credentials)
sheet = client.open_by_key(spreadsheet_id).sheet1
sheet.append_row(transaction_data)
record_transaction('your_spreadsheet_id', ['2022-07-01', 'Groceries', 50.00])
9. PDF操作
描述:將多個PDF文件合并為一個。
腳本:
import PyPDF2
def merge_pdfs(pdf_list, output_file):
merger = PyPDF2.PdfFileMerger()
for pdf in pdf_list:
merger.append(pdf)
merger.write(output_file)
merger.close()
merge_pdfs(['file1.pdf', 'file2.pdf', 'file3.pdf'], 'merged.pdf')
10. 桌面通知
描述:發(fā)送桌面通知以提醒和警報。
腳本:
from plyer import notification
def send_notification(title, message):
notification.notify(
title=title,
message=message,
app_icnotallow=None,
timeout=10,
)
send_notification('Reminder', 'Time to take a break!')
總結(jié)
這些Python腳本展示了Python語言在自動化日常任務(wù)方面的多樣性。通過將這些腳本集成到工作流程中,可以提高生產(chǎn)力,節(jié)省時間,并減輕重復(fù)性任務(wù)的負(fù)擔(dān)。嘗試探索這些自動化腳本,了解Python如何讓你的生活更輕松。