十個(gè)Python腳本,輕松實(shí)現(xiàn)日常任務(wù)自動(dòng)化
Python是一種通用編程語(yǔ)言,以其簡(jiǎn)單性和易讀性而著稱。它被廣泛應(yīng)用于從網(wǎng)絡(luò)開(kāi)發(fā)到數(shù)據(jù)分析等各個(gè)領(lǐng)域。在本文中,我們將探討10個(gè)Python腳本,它們可以自動(dòng)執(zhí)行常見(jiàn)任務(wù),讓你的生活更輕松。
1. 使用Pandas進(jìn)行數(shù)據(jù)分析
Pandas是一個(gè)功能強(qiáng)大的數(shù)據(jù)分析庫(kù)。只需幾行代碼,你就可以讀取、清洗和分析來(lái)自CSV文件或數(shù)據(jù)庫(kù)等各種來(lái)源的數(shù)據(jù)。下面是一個(gè)示例腳本。
import pandas as pd
# 從CSV文件讀取數(shù)據(jù)
data = pd.read_csv('data.csv')
# 執(zhí)行基本分析
mean = data['column_name'].mean()
print(f"Mean: {mean}")2. 使用BeautifulSoup進(jìn)行網(wǎng)頁(yè)抓取
BeautifulSoup 是一個(gè)用于網(wǎng)頁(yè)抓取的Python庫(kù)。它可以讓你輕松地從網(wǎng)站中提取數(shù)據(jù)。下面是一個(gè)簡(jiǎn)單的網(wǎng)頁(yè)抓取腳本。
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 從網(wǎng)頁(yè)中提取數(shù)據(jù)
data = soup.find('div', class_='content')
print(data.text)3. 文件重命名
當(dāng)你需要根據(jù)特定標(biāo)準(zhǔn)對(duì)文件夾中的多個(gè)文件進(jìn)行重命名時(shí),此腳本會(huì)非常方便。例如,你可以添加前綴和后綴,或替換文件名中的文本。
import os
folder_path = '/path/to/folder'
for filename in os.listdir(folder_path):
if filename.startswith('prefix_'):
new_filename = filename.replace('prefix_', 'new_prefix_')
os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))4. 使用Pillow調(diào)整圖像大小
Pillow是一個(gè)Python圖像處理庫(kù),可以簡(jiǎn)化圖像處理。此腳本可以將一批圖像調(diào)整到指定的分辨率或長(zhǎng)寬比。
from PIL import Image
import os
input_folder = '/path/to/images'
output_folder = '/path/to/resized_images'
desired_size = (100, 100)
for filename in os.listdir(input_folder):
with Image.open(os.path.join(input_folder, filename)) as img:
img.thumbnail(desired_size)
img.save(os.path.join(output_folder, filename))5. 使用ReportLab創(chuàng)建PDF
ReportLab是一個(gè)使用Python創(chuàng)建PDF文檔的庫(kù)。你可以從文本或HTML內(nèi)容生成PDF文件。下面是一個(gè)基本的示例。
from reportlab.pdfgen import canvas
pdf_file = 'output.pdf'
text = 'Hello, this is a sample PDF.'
c = canvas.Canvas(pdf_file)
c.drawString(100, 750, text)
c.save()6. 使用smtplib發(fā)送電子郵件
如果需要自動(dòng)發(fā)送電子郵件,Python的smtplib庫(kù)可以提供幫助。此腳本可以幫助你以編程方式發(fā)送電子郵件。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
smtp_server = 'smtp.example.com'
sender_email = 'your_email@example.com'
receiver_email = 'recipient@example.com'
password = 'your_password'
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'Sample Email Subject'
body = 'This is a sample email message.'
message.attach(MIMEText(body, 'plain'))
with smtplib.SMTP(smtp_server, 587) as server:
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())7. 數(shù)據(jù)備份腳本
自動(dòng)備份文件和目錄,確保數(shù)據(jù)安全。
import shutil
source_folder = '/path/to/source_folder'
backup_folder = '/path/to/backup_folder'
shutil.copytree(source_folder, backup_folder)8. 密碼生成器
生成強(qiáng)大、隨機(jī)的密碼以增強(qiáng)安全性。
import random
import string
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for _ in range(length))
password = generate_password()
print(password)9. 簡(jiǎn)單的Web服務(wù)器
創(chuàng)建一個(gè)基本的HTTP服務(wù)器,用于測(cè)試和開(kāi)發(fā)目的。
import http.server
import socketserver
port = 8000
with socketserver.TCPServer(('', port), http.server.SimpleHTTPRequestHandler) as httpd:
print(f"Serving at port {port}")
httpd.serve_forever()10. 使用SQLite備份和恢復(fù)數(shù)據(jù)庫(kù)
SQLite是一個(gè)輕量級(jí)、基于磁盤的數(shù)據(jù)庫(kù)。它不需要單獨(dú)的服務(wù)器,使用一種獨(dú)特的SQL變體。它可用于許多應(yīng)用程序的內(nèi)部數(shù)據(jù)存儲(chǔ),也可以用于在使用更大的數(shù)據(jù)庫(kù)(如PostgreSQL或Oracle)之前進(jìn)行原型設(shè)計(jì)。
下面是一個(gè)使用Python備份和恢復(fù)SQLite數(shù)據(jù)庫(kù)的示例腳本。
import sqlite3
import shutil
# 數(shù)據(jù)庫(kù)文件路徑
source_db_file = 'source.db'
backup_db_file = 'backup.db'
# 創(chuàng)建SQLite數(shù)據(jù)庫(kù)備份的函數(shù)
def backup_database():
try:
shutil.copy2(source_db_file, backup_db_file)
print("Backup successful.")
except Exception as e:
print(f"Backup failed: {str(e)}")
# 從備份中恢復(fù)SQLite數(shù)據(jù)庫(kù)的函數(shù)
def restore_database():
try:
shutil.copy2(backup_db_file, source_db_file)
print("Restore successful.")
except Exception as e:
print(f"Restore failed: {str(e)}")
# 使用方法
while True:
print("Options:")
print("1. Backup Database")
print("2. Restore Database")
print("3. Quit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
backup_database()
elif choice == '2':
restore_database()
elif choice == '3':
break
else:
print("Invalid choice. Please enter 1, 2, or 3.")在這段代碼中:
- backup_database()函數(shù)會(huì)復(fù)制SQLite數(shù)據(jù)庫(kù)源文件并將其命名為備份文件。運(yùn)行此函數(shù)可創(chuàng)建數(shù)據(jù)庫(kù)備份。
- restore_database()函數(shù)會(huì)將備份文件復(fù)制回源文件,從而有效地將數(shù)據(jù)庫(kù)恢復(fù)到創(chuàng)建備份時(shí)的狀態(tài)。
- 用戶可以選擇備份數(shù)據(jù)庫(kù)、恢復(fù)數(shù)據(jù)庫(kù)或退出程序。
- 你可以調(diào)整source_db_file和backup_db_file變量來(lái)指定SQLite源文件和備份數(shù)據(jù)庫(kù)文件的路徑。
以上就是10個(gè)實(shí)用的Python腳本,可以幫助你自動(dòng)完成日常任務(wù)。



































