Python自動化處理日常任務(wù)的示例代碼
1. 自動化文件管理
1.1 批量重命名文件
假設(shè)你有一批文件,文件名需要按一定規(guī)則批量修改,可以使用 os 和 re 庫來實(shí)現(xiàn)。
import os
import re
# 設(shè)置目錄路徑
directory = 'C:/path/to/your/files'
# 獲取文件列表
files = os.listdir(directory)
# 批量重命名文件
for filename in files:
new_name = re.sub(r'old_pattern', 'new_pattern', filename) # 替換文件名中的內(nèi)容
os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
print("文件重命名完成!")
1.2 自動分類文件
根據(jù)文件擴(kuò)展名自動將文件分類到不同的文件夾中。
import os
import shutil
# 設(shè)置目錄路徑
directory = 'C:/path/to/your/files'
# 獲取文件列表
files = os.listdir(directory)
# 定義文件分類規(guī)則
file_types = {
'images': ['.jpg', '.jpeg', '.png', '.gif'],
'documents': ['.pdf', '.txt', '.docx'],
'audio': ['.mp3', '.wav']
}
# 創(chuàng)建文件夾(如果不存在)
for folder in file_types:
if not os.path.exists(os.path.join(directory, folder)):
os.makedirs(os.path.join(directory, folder))
# 移動文件
for filename in files:
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
moved = False
for folder, extensions in file_types.items():
if any(filename.endswith(ext) for ext in extensions):
shutil.move(file_path, os.path.join(directory, folder, filename))
moved = True
break
if not moved:
print(f"文件 {filename} 沒有分類!")
print("文件分類完成!")2. 自動化定時任務(wù)
2.1 使用 schedule 庫定時執(zhí)行任務(wù)
schedule 是一個 Python 庫,專門用于調(diào)度定時任務(wù)。你可以使用它來設(shè)置定時執(zhí)行的任務(wù)。
import schedule
import time
# 定義要執(zhí)行的任務(wù)
def job():
print("任務(wù)開始執(zhí)行!")
# 每隔 10 秒執(zhí)行一次任務(wù)
schedule.every(10).seconds.do(job)
# 持續(xù)運(yùn)行任務(wù)
while True:
schedule.run_pending()
time.sleep(1)
2.2 使用 APScheduler 執(zhí)行復(fù)雜定時任務(wù)
APScheduler 是一個功能更強(qiáng)大的調(diào)度任務(wù)庫,支持多種調(diào)度方式。
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
# 定義要執(zhí)行的任務(wù)
def print_time():
print(f"當(dāng)前時間:{datetime.datetime.now()}")
# 創(chuàng)建調(diào)度器
scheduler = BlockingScheduler()
# 添加任務(wù),定時每分鐘執(zhí)行
scheduler.add_job(print_time, 'interval', minutes=1)
# 啟動調(diào)度器
scheduler.start()
3. 自動化發(fā)送郵件
使用 smtplib 庫,可以自動化發(fā)送郵件,比如定時向客戶或團(tuán)隊(duì)成員發(fā)送報(bào)告。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(subject, body, to_email):
from_email = "your_email@gmail.com"
password = "your_password"
# 設(shè)置郵件內(nèi)容
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# 發(fā)送郵件
try:
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()
print("郵件發(fā)送成功!")
except Exception as e:
print(f"郵件發(fā)送失?。簕e}")
# 調(diào)用函數(shù)發(fā)送郵件
send_email("自動化報(bào)告", "這是自動化發(fā)送的郵件內(nèi)容", "recipient_email@example.com")4. 自動化網(wǎng)絡(luò)爬蟲
使用 requests 和 BeautifulSoup 庫,可以自動化爬取網(wǎng)頁內(nèi)容,并將其存儲到文件中。
import requests
from bs4 import BeautifulSoup
# 定義爬取目標(biāo)網(wǎng)址
url = "https://example.com"
# 發(fā)送 HTTP 請求獲取網(wǎng)頁內(nèi)容
response = requests.get(url)
# 解析網(wǎng)頁內(nèi)容
soup = BeautifulSoup(response.text, 'html.parser')
# 獲取頁面標(biāo)題
title = soup.title.string
# 打印標(biāo)題
print(f"網(wǎng)頁標(biāo)題: {title}")5. 自動化數(shù)據(jù)處理
5.1 使用 Pandas 庫處理數(shù)據(jù)
如果你經(jīng)常需要處理 CSV 文件或 Excel 文件,可以使用 Pandas 庫來實(shí)現(xiàn)數(shù)據(jù)的讀取、處理和導(dǎo)出。
import pandas as pd
# 讀取 CSV 文件
df = pd.read_csv('data.csv')
# 進(jìn)行數(shù)據(jù)處理(例如:篩選大于 100 的值)
df_filtered = df[df['column_name'] > 100]
# 保存處理后的數(shù)據(jù)到新的 CSV 文件
df_filtered.to_csv('filtered_data.csv', index=False)
print("數(shù)據(jù)處理完成!")
5.2 定時備份數(shù)據(jù)庫
可以通過 Python 腳本定時備份數(shù)據(jù)庫,減少人工干預(yù)。
import mysql.connector
import datetime
import os
def backup_database():
# 數(shù)據(jù)庫連接配置
db = mysql.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="your_database"
)
# 創(chuàng)建備份文件名
backup_filename = f"backup_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.sql"
# 使用 mysqldump 進(jìn)行備份
os.system(f"mysqldump -u your_user -p'your_password' your_database > {backup_filename}")
print(f"數(shù)據(jù)庫備份完成!備份文件: {backup_filename}")
# 定時備份
backup_database()6. 自動化圖像處理
如果你需要自動處理圖像文件(例如,批量調(diào)整大小、轉(zhuǎn)換格式等),可以使用 Pillow 庫。
from PIL import Image
import os
# 設(shè)置圖像目錄
image_directory = 'C:/path/to/your/images'
# 獲取所有圖像文件
files = os.listdir(image_directory)
# 批量調(diào)整圖像大小
for filename in files:
if filename.endswith('.jpg'):
image_path = os.path.join(image_directory, filename)
with Image.open(image_path) as img:
img = img.resize((800, 600)) # 調(diào)整大小為 800x600
img.save(os.path.join(image_directory, f"resized_{filename}"))
print("圖像處理完成!")7. 自動化 Web 操作
如果你需要自動化與網(wǎng)頁的交互,可以使用 Selenium 來模擬瀏覽器操作。
from selenium import webdriver
# 設(shè)置 WebDriver
driver = webdriver.Chrome(executable_path="path/to/chromedriver")
# 打開網(wǎng)頁
driver.get("https://example.com")
# 查找并點(diǎn)擊一個按鈕
button = driver.find_element_by_xpath("http://button[@id='submit']")
button.click()
# 獲取網(wǎng)頁內(nèi)容
page_content = driver.page_source
print(page_content)
# 關(guān)閉瀏覽器
driver.quit()總結(jié)
使用 Python 自動化日常任務(wù)可以極大地提高效率并減少重復(fù)性工作。通過 Python 中的各種庫(如 os、shutil、schedule、smtplib、requests、pandas、Pillow 等),你可以輕松實(shí)現(xiàn)文件管理、定時任務(wù)、郵件發(fā)送、網(wǎng)頁爬取、數(shù)據(jù)處理等多種自動化任務(wù)。
到此這篇關(guān)于Python自動化處理日常任務(wù)的示例代碼的文章就介紹到這了,更多相關(guān)Python自動化處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)圖片處理和特征提取詳解
這篇文章主要介紹了python實(shí)現(xiàn)圖片處理和特征提取詳解,文中向大家分享了Python導(dǎo)入圖片,將圖像轉(zhuǎn)化為二維矩陣,模糊化圖片等Python對圖像的操作,具有一定參考價值,需要的朋友可以了解下。2017-11-11
python項(xiàng)目導(dǎo)入open3d后報(bào)錯ImportError:DLL load failed:找不到
這篇文章主要介紹了python項(xiàng)目導(dǎo)入open3d后報(bào)錯ImportError:DLL load failed:找不到指定的模塊問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
Python使用Selenium+BeautifulSoup爬取淘寶搜索頁
這篇文章主要為大家詳細(xì)介紹了Python使用Selenium+BeautifulSoup爬取淘寶搜索頁,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02
Python輕松實(shí)現(xiàn)將Excel表格完美轉(zhuǎn)換為Word
數(shù)據(jù)管理與轉(zhuǎn)換在日常工作中扮演著重要角色,本文將教你如何使用 Spire.XLS for Python 和 Spire.Doc for Python 庫,輕松將 Excel 數(shù)據(jù)導(dǎo)出并在 Word 中生成美觀的表格,感興趣的小伙伴可以了解下2026-02-02
Python OpenCV實(shí)現(xiàn)邊緣檢測
這篇文章主要為大家詳細(xì)介紹了Python OpenCV實(shí)現(xiàn)邊緣檢測,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
Python全景系列之?dāng)?shù)據(jù)類型大盤點(diǎn)
這篇文章主要為大家介紹了Python全景系列之?dāng)?shù)據(jù)類型的盤點(diǎn)解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05

