十個Python腳本,輕松實現(xiàn)日常任務(wù)自動化
Python是一種通用編程語言,以其簡單性和易讀性而著稱。它被廣泛應(yīng)用于從網(wǎng)絡(luò)開發(fā)到數(shù)據(jù)分析等各個領(lǐng)域。在本文中,我們將探討10個Python腳本,它們可以自動執(zhí)行常見任務(wù),讓你的生活更輕松。
1. 使用Pandas進行數(shù)據(jù)分析
Pandas是一個功能強大的數(shù)據(jù)分析庫。只需幾行代碼,你就可以讀取、清洗和分析來自CSV文件或數(shù)據(jù)庫等各種來源的數(shù)據(jù)。下面是一個示例腳本。
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進行網(wǎng)頁抓取
BeautifulSoup 是一個用于網(wǎng)頁抓取的Python庫。它可以讓你輕松地從網(wǎng)站中提取數(shù)據(jù)。下面是一個簡單的網(wǎng)頁抓取腳本。
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 從網(wǎng)頁中提取數(shù)據(jù)
data = soup.find('div', class_='content')
print(data.text)
3. 文件重命名
當你需要根據(jù)特定標準對文件夾中的多個文件進行重命名時,此腳本會非常方便。例如,你可以添加前綴和后綴,或替換文件名中的文本。
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是一個Python圖像處理庫,可以簡化圖像處理。此腳本可以將一批圖像調(diào)整到指定的分辨率或長寬比。
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是一個使用Python創(chuàng)建PDF文檔的庫。你可以從文本或HTML內(nèi)容生成PDF文件。下面是一個基本的示例。
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ā)送電子郵件
如果需要自動發(fā)送電子郵件,Python的smtplib庫可以提供幫助。此腳本可以幫助你以編程方式發(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ù)備份腳本
自動備份文件和目錄,確保數(shù)據(jù)安全。
import shutil
source_folder = '/path/to/source_folder'
backup_folder = '/path/to/backup_folder'
shutil.copytree(source_folder, backup_folder)
8. 密碼生成器
生成強大、隨機的密碼以增強安全性。
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. 簡單的Web服務(wù)器
創(chuàng)建一個基本的HTTP服務(wù)器,用于測試和開發(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ù)庫
SQLite是一個輕量級、基于磁盤的數(shù)據(jù)庫。它不需要單獨的服務(wù)器,使用一種獨特的SQL變體。它可用于許多應(yīng)用程序的內(nèi)部數(shù)據(jù)存儲,也可以用于在使用更大的數(shù)據(jù)庫(如PostgreSQL或Oracle)之前進行原型設(shè)計。
下面是一個使用Python備份和恢復(fù)SQLite數(shù)據(jù)庫的示例腳本。
import sqlite3
import shutil
# 數(shù)據(jù)庫文件路徑
source_db_file = 'source.db'
backup_db_file = 'backup.db'
# 創(chuàng)建SQLite數(shù)據(jù)庫備份的函數(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ù)庫的函數(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ù)會復(fù)制SQLite數(shù)據(jù)庫源文件并將其命名為備份文件。運行此函數(shù)可創(chuàng)建數(shù)據(jù)庫備份。
- restore_database()函數(shù)會將備份文件復(fù)制回源文件,從而有效地將數(shù)據(jù)庫恢復(fù)到創(chuàng)建備份時的狀態(tài)。
- 用戶可以選擇備份數(shù)據(jù)庫、恢復(fù)數(shù)據(jù)庫或退出程序。
- 你可以調(diào)整source_db_file和backup_db_file變量來指定SQLite源文件和備份數(shù)據(jù)庫文件的路徑。
以上就是10個實用的Python腳本,可以幫助你自動完成日常任務(wù)。