今天给大家分享40个 python 日常使用最频繁的自动化脚本。
21、Excel 数据处理脚本(读取和写入数据):
import openpyxl
def read_excel_data(file_path, sheet_name):
workbook = openpyxl.load_workbook(file_path)
sheet = workbook[sheet_name]
data = []
for row in sheet.iter_rows(values_only=True):
data.append(row)
workbook.close()
return data
def write_excel_data(file_path, sheet_name, new_data):
workbook = openpyxl.load_workbook(file_path)
sheet = workbook[sheet_name]
for row in new_data:
sheet.append(row)
workbook.save(file_path)
workbook.close()
# 示例用法
data = read_excel_data('example.xlsx', 'Sheet1')
new_data = [('New Row 1', 100), ('New Row 2', 200)]
write_excel_data('example.xlsx', 'Sheet1', new_data)
该脚本可用于读取 Excel 文件中的数据,并向其中写入新的数据。
22、文件夹大小统计脚本:
import os
def get_folder_size(folder_path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(folder_path):
for f in filenames:
file_path = os.path.join(dirpath, f)
total_size += os.path.getsize(file_path)
return total_size
# 示例用法
size = get_folder_size('/your/folder')
print(f"Folder size: {size} bytes")
能够计算指定文件夹及其子文件夹内所有文件的总大小。
23、自动化网页截图脚本:
from selenium import webdriver
def take_webpage_screenshot(url, screenshot_path):
driver = webdriver.Chrome() # 需要安装 Chrome 驱动并配置好环境变量
driver.get(url)
driver.save_screenshot(screenshot_path)
driver.quit()
# 示例用法
take_webpage_screenshot('https://www.example.com', 'screenshot.png')
使用 Selenium 库对指定网页进行截图并保存。
24、文本文件行数统计脚本:
defcount_lines_in_text_file(file_path):
withopen(file_path, 'r') as file:
line_count = sum(1for line in file)
return line_count
# 示例用法
lines = count_lines_in_text_file('/your/text.txt')
print(f"Number of lines: {lines}")
统计文本文件中的行数。
25、批量解压文件脚本(以 zip 文件为例)
import zipfile
def batch_unzip_files(folder_path):
for file in os.listdir(folder_path):
if file.endswith('.zip'):
zip_file_path = os.path.join(folder_path, file)
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(folder_path)
# 示例用法
batch_unzip_files('/your/zip/folder')
将指定文件夹内的所有 zip 文件解压到该文件夹。
26、自动化创建数据库表脚本(以 SQLite 为例):
import sqlite3
def create_sqlite_table(database_path, table_name, columns):
conn = sqlite3.connect(database_path)
cursor = conn.cursor()
column_definitions = ', '.join([f'{col[0]} {col[1]}' for col in columns])
create_table_query = f'CREATE TABLE {table_name} ({column_definitions})'
cursor.execute(create_table_query)
conn.commit()
conn.close()
# 示例用法
columns = [('id', 'INTEGER PRIMARY KEY'), ('name', 'TEXT'), ('age', 'INTEGER')]
create_sqlite_table('example.db', 'people', columns)
创建一个 SQLite 数据库表,可指定表名和列信息。
27、系统进程监控脚本:
import psutil
defmonitor_processes():
for proc in psutil.process_iter():
try:
process_info = proc.as_dict(attrs=['pid', 'name', 'cpu_percent'])
print(f"PID: {process_info['pid']}, Name: {process_info['name']}, CPU Usage: {process_info['cpu_percent']}%")
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
# 示例用法
monitor_processes()
获取当前系统中运行的进程信息,包括进程 ID、名称和 CPU 使用率。
28、自动化生成二维码脚本:
import pyqrcode
def generate_qr_code(data, output_path):
qr = pyqrcode.create(data)
qr.png(output_path, scale=6)
# 示例用法
generate_qr_code('https://www.example.com', 'qr_code.png')
根据给定的数据生成二维码图片并保存。
29、文本加密脚本(简单的凯撒密码示例):
def caesar_cipher_encrypt(text, shift):
encrypted_text = ""
forcharin text:
ifchar.isalpha():
ifchar.isupper():
encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65)
else:
encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97)
else:
encrypted_text += char
return encrypted_text
# 示例用法
encrypted = caesar_cipher_encrypt('Hello, World!', 3)
print(encrypted)
使用凯撒密码对文本进行加密。
30、自动化数据可视化脚本(绘制柱状图):
import matplotlib.pyplot as plt
def plot_bar_chart(x_data, y_data):
plt.bar(x_data, y_data)
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Bar Chart')
plt.show()
# 示例用法
x = ['A', 'B', 'C']
y = [10, 20, 30]
plot_bar_chart(x, y)
根据给定的数据绘制柱状图进行数据可视化。
31、自动化文件下载脚本:
import requests
defdownload_file(url, save_path):
response = requests.get(url)
withopen(save_path, 'wb') as file:
file.write(response.content)
# 示例用法
download_file('https://example.com/file.txt', 'downloaded_file.txt')
从指定的 URL 下载文件并保存到本地。
32、自动化删除空文件夹脚本:
import os
defremove_empty_folders(root_folder):
for root, dirs, files in os.walk(root_folder, topdown=False):
fordirin dirs:
folder_path = os.path.join(root, dir)
ifnot os.listdir(folder_path):
os.rmdir(folder_path)
# 示例用法
remove_empty_folders('/your/directory')
递归地删除指定目录下的所有空文件夹。
33、自动化修改文件权限脚本(以 Linux 系统为例):
import os
defchange_file_permissions(file_path, permissions):
os.chmod(file_path, permissions)
# 示例用法
change_file_permissions('/your/file.txt', 0o644) # 设置文件权限为 -rw-r--r--
修改指定文件的权限。
34、自动化生成 HTML 页面脚本(简单示例):
def create_html_page(title, content, output_path):
html = f"""
<!DOCTYPE html>
<html>
<head>
<title>{title}</title>
</head>
<body>
{content}
</body>
</html>
"""
with open(output_path, 'w') as file:
file.write(html)
# 示例用法
create_html_page('My Page', '<h1>Hello, World!</h1>', 'index.html')
根据给定的标题、内容生成一个简单的 HTML 页面并保存。
35、自动化提取音频文件中的文本脚本(使用 speech_recognition 库):
import speech_recognition as sr
deftranscribe_audio(audio_path):
r = sr.Recognizer()
with sr.AudioFile(audio_path) as source:
audio = r.record(source)
try:
text = r.recognize_google(audio)
return text
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print(f"Could not request results from Google Speech Recognition service; {e}")
# 示例用法
text = transcribe_audio('/your/audio.wav')
print(text)
从音频文件中提取文本内容(需联网使用 Google 语音识别服务)。
36、自动化整理数据库数据脚本(以 MySQL 为例,清理重复记录):
import mysql.connector
def clean_duplicate_records(database, table, columns):
connection = mysql.connector.connect(
host='your_host',
user='your_user',
password='your_password',
database=database
)
cursor = connection.cursor()
columns_str = ', '.join(columns)
# 使用临时表删除重复记录
query = f"""
CREATE TEMPORARY TABLE temp_table AS
SELECT {columns_str}, MIN(id) AS min_id
FROM {table}
GROUP BY {columns_str};
DELETE FROM {table}
WHERE id NOT IN (SELECT min_id FROM temp_table);
DROP TABLE temp_table;
"""
cursor.execute(query)
connection.commit()
cursor.close()
connection.close()
# 示例用法
clean_duplicate_records('your_database', 'your_table', ['column1', 'column2'])
清理 MySQL 数据库表中的重复记录。
37、自动化生成随机数列表脚本:
import random
defgenerate_random_numbers_list(length, min_value, max_value):
return [random.randint(min_value, max_value) for _ inrange(length)]
# 示例用法
random_numbers = generate_random_numbers_list(10, 1, 100)
print(random_numbers)
生成指定长度、在给定范围内的随机数列表。
38、自动化检测文件类型脚本:
import magic
defdetect_file_type(file_path):
file_type = magic.from_file(file_path, mime=True)
return file_type
# 示例用法
file_type = detect_file_type('/your/file.jpg')
print(file_type)
使用 magic 库检测文件的类型。
39、自动化备份系统配置脚本(以 Linux 系统为例,备份 /etc 目录):
import shutil
def backup_system_config(source_dir, destination_dir):
shutil.copytree(source_dir, destination_dir)
# 示例用法
backup_system_config('/etc', '/backup/etc')
备份 Linux 系统的 /etc 目录到指定位置。
40、自动化生成斐波那契数列脚本:
defgenerate_fibonacci_sequence(length):
sequence = []
a, b = 0, 1
for _ inrange(length):
sequence.append(a)
a, b = b, a + b
return sequence
# 示例用法
fibonacci = generate_fibonacci_sequence(10)
print(fibonacci)
生成指定长度的斐波那契数列。