十個常見的Python腳本詳細(xì)介紹及代碼舉例
1. 批量重命名文件
介紹: 該腳本用于批量重命名指定目錄下的文件,例如將所有 ".txt" 文件重命名為 ".md" 文件。
import os
def batch_rename(directory, old_ext, new_ext):
"""批量重命名文件擴(kuò)展名。
Args:
directory: 要處理的目錄路徑。
old_ext: 要替換的舊擴(kuò)展名。
new_ext: 要替換的新擴(kuò)展名。
"""
for filename in os.listdir(directory):
if filename.endswith(old_ext):
base_name = os.path.splitext(filename)[0]
new_filename = base_name + new_ext
old_path = os.path.join(directory, filename)
new_path = os.path.join(directory, new_filename)
os.rename(old_path, new_path)
# 示例用法:將當(dāng)前目錄下所有 ".txt" 文件重命名為 ".md" 文件
batch_rename(".", ".txt", ".md")2. 下載網(wǎng)頁圖片
介紹: 該腳本用于下載指定網(wǎng)頁上的所有圖片,并保存到本地目錄。
import requests
from bs4 import BeautifulSoup
import os
def download_images(url, save_dir):
"""下載網(wǎng)頁上的所有圖片。
Args:
url: 要下載圖片的網(wǎng)頁地址。
save_dir: 保存圖片的目錄路徑。
"""
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 創(chuàng)建保存目錄
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 找到所有圖片標(biāo)簽
img_tags = soup.find_all('img')
# 下載每張圖片
for i, img_tag in enumerate(img_tags):
img_url = img_tag.get('src')
if img_url:
img_data = requests.get(img_url).content
img_name = f"image_{i+1}.jpg"
img_path = os.path.join(save_dir, img_name)
with open(img_path, 'wb') as f:
f.write(img_data)
print(f"Downloaded: {img_name}")
# 示例用法:下載百度首頁的圖片
download_images("https://www.baidu.com", "baidu_images")3. 發(fā)送郵件通知
介紹: 該腳本用于發(fā)送郵件通知,例如在腳本執(zhí)行完畢后發(fā)送郵件通知管理員。
import smtplib
from email.mime.text import MIMEText
def send_email(sender_email, sender_password, receiver_email, subject, message):
"""發(fā)送郵件通知。
Args:
sender_email: 發(fā)送方郵箱地址。
sender_password: 發(fā)送方郵箱密碼。
receiver_email: 接收方郵箱地址。
subject: 郵件主題。
message: 郵件內(nèi)容。
"""
msg = MIMEText(message, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(sender_email, sender_password)
smtp.send_message(msg)
print("郵件發(fā)送成功!")
except Exception as e:
print(f"郵件發(fā)送失?。簕e}")
# 示例用法:發(fā)送郵件通知
send_email("your_email@gmail.com", "your_password", "receiver@example.com", "腳本執(zhí)行完畢", "腳本已成功執(zhí)行!")4. 讀取 CSV 文件
介紹: 該腳本用于讀取 CSV 文件,并可以根據(jù)需要對數(shù)據(jù)進(jìn)行處理和分析。
import csv
def read_csv(file_path):
"""讀取 CSV 文件。
Args:
file_path: CSV 文件路徑。
"""
with open(file_path, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
# 跳過標(biāo)題行
next(reader)
for row in reader:
print(row)
# 示例用法:讀取名為 "data.csv" 的 CSV 文件
read_csv("data.csv")5. 寫入 CSV 文件
介紹: 該腳本用于將數(shù)據(jù)寫入 CSV 文件,可以用于數(shù)據(jù)存儲和導(dǎo)出。
import csv
def write_csv(file_path, data):
"""將數(shù)據(jù)寫入 CSV 文件。
Args:
file_path: CSV 文件路徑。
data: 要寫入的數(shù)據(jù),格式為列表的列表。
"""
with open(file_path, 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
# 示例用法:將數(shù)據(jù)寫入名為 "data.csv" 的 CSV 文件
data = [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "London"],
]
write_csv("data.csv", data)6. 爬取網(wǎng)頁數(shù)據(jù)
介紹: 該腳本用于爬取網(wǎng)頁數(shù)據(jù),例如新聞標(biāo)題、商品價格等,并可以將數(shù)據(jù)保存到本地或數(shù)據(jù)庫。
import requests
from bs4 import BeautifulSoup
def scrape_website(url):
"""爬取網(wǎng)頁數(shù)據(jù)。
Args:
url: 要爬取數(shù)據(jù)的網(wǎng)頁地址。
"""
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取數(shù)據(jù),例如新聞標(biāo)題
titles = [title.text.strip() for title in soup.find_all('h2', class_='news-title')]
# 打印提取的數(shù)據(jù)
for title in titles:
print(title)
# 示例用法:爬取新浪新聞首頁的新聞標(biāo)題
scrape_website("https://news.sina.com.cn/")7. 自動化測試
介紹: 該腳本用于自動化測試軟件或網(wǎng)站的功能,例如登錄測試、表單提交測試等。
from selenium import webdriver
def test_login(url, username, password):
"""測試網(wǎng)站登錄功能。
Args:
url: 要測試的網(wǎng)站地址。
username: 登錄用戶名。
password: 登錄密碼。
"""
driver = webdriver.Chrome()
driver.get(url)
# 找到用戶名和密碼輸入框,并輸入用戶名和密碼
username_input = driver.find_element_by_id("username")
password_input = driver.find_element_by_id("password")
username_input.send_keys(username)
password_input.send_keys(password)
# 找到登錄按鈕,并點擊
login_button = driver.find_element_by_id("login-button")
login_button.click()
# 檢查是否登錄成功
if driver.current_url == "https://www.example.com/dashboard":
print("登錄成功!")
else:
print("登錄失敗!")
driver.quit()
# 示例用法:測試 example.com 網(wǎng)站的登錄功能
test_login("https://www.example.com/login", "testuser", "testpassword")8. 圖像處理
介紹: 該腳本用于圖像處理,例如裁剪、縮放、添加水印等。
from PIL import Image
def resize_image(image_path, width, height):
"""縮放圖片大小。
Args:
image_path: 圖片路徑。
width: 新的寬度。
height: 新的高度。
"""
img = Image.open(image_path)
img = img.resize((width, height))
img.save("resized_" + image_path)
# 示例用法:將圖片 "image.jpg" 縮放為 200x200 像素
resize_image("image.jpg", 200, 200)9. 數(shù)據(jù)可視化
介紹: 該腳本用于數(shù)據(jù)可視化,例如繪制圖表、生成報表等,可以更直觀地展示數(shù)據(jù)。
import matplotlib.pyplot as plt
def plot_chart(x, y):
"""繪制折線圖。
Args:
x: x 軸數(shù)據(jù)。
y: y 軸數(shù)據(jù)。
"""
plt.plot(x, y)
plt.xlabel("X 軸")
plt.ylabel("Y 軸")
plt.title("折線圖")
plt.show()
# 示例用法:繪制 x=[1,2,3], y=[4,5,6] 的折線圖
plot_chart([1, 2, 3], [4, 5, 6])10. 創(chuàng)建簡單的 Web 應(yīng)用
介紹: 該腳本使用 Flask 框架創(chuàng)建一個簡單的 Web 應(yīng)用,例如顯示 "Hello, world!" 的頁面。
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, world!"
if __name__ == "__main__":
app.run(debug=True)注意: 以上代碼示例僅供參考,實際應(yīng)用中需要根據(jù)具體需求進(jìn)行修改和完善。部署爬蟲相關(guān)代碼需要遵守 robots 協(xié)議, 并注意數(shù)據(jù)安全。
總結(jié)
到此這篇關(guān)于十個常見的Python腳本的文章就介紹到這了,更多相關(guān)Python腳本介紹及代碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于pyinstaller超級加密操作(加殼和轉(zhuǎn)c)
這篇文章主要介紹了基于pyinstaller超級加密操作 (加殼和轉(zhuǎn)c),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
在Python的Django框架中實現(xiàn)Hacker News的一些功能
這篇文章主要介紹了在Python的Django框架中實現(xiàn)Hacker News的一些功能,包括投票“頂”評論等功能,需要的朋友可以參考下2015-04-04
python-docx把dataframe表格添加到word文件中
用Python-docx庫,可以輕松地添加表格到Word文檔中,本文主要介紹了python-docx把dataframe表格添加到word文件中,感興趣的可以了解一下2023-08-08
windows系統(tǒng)中python使用rar命令壓縮多個文件夾示例
這篇文章主要介紹了windows系統(tǒng)中python使用rar命令壓縮多個文件夾示例,需要的朋友可以參考下2014-05-05

