跳到主要内容
20 个实用 Python 自动化脚本技巧 | 极客日志
Python AI
20 个实用 Python 自动化脚本技巧 20 个实用 Python 自动化脚本技巧涵盖文件管理、网络抓取、文本处理、邮件自动化、Excel 操作、数据库交互、社交媒体、系统任务、图像编辑、网络自动化、数据转换、PDF 操作、GUI 自动化、测试自动化、云服务、财务、机器学习、音视频处理、游戏自动化及安全性等领域。每个技巧均提供对应的 Python 代码示例,帮助开发者简化重复性工作,提升生产力。
静心 发布于 2025/2/7 更新于 2026/6/2 19 浏览前言
你是否厌倦了在日常工作中执行重复的任务?Python 凭借其简单性和多功能性,可能是解决你问题的答案。
在本文中,我们将探讨 20 个 Python 脚本及其代码,这些脚本可以帮助你自动化各种任务,提高生产力。无论你是开发人员、数据分析师,还是只是希望简化工作流程的人,这些脚本都能满足你的需求。
简介
Python 是一种流行的编程语言,以其简单性和可读性而著称。它提供了大量的库和模块,使其成为自动化各种任务的绝佳选择。
让我们深入探索自动化的世界,发现 20 个 Python 脚本,这些脚本可以简化你的工作,为你节省时间和精力。
1. 文件管理自动化
1.1 在目录中按扩展名排序文件
import os
from shutil import move
def sort_files (directory_path ):
for filename in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, filename)):
file_extension = filename.split('.' )[-1 ]
destination_directory = os.path.join(directory_path, file_extension)
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
move(os.path.join(directory_path, filename), os.path.join(destination_directory, filename))
描述: 这个 Python 脚本根据文件扩展名将目录中的文件组织到子目录中。它识别文件扩展名并将文件移动到相应的子目录。这对于整理下载文件夹或组织特定项目的文件很有用。
1.2 删除空文件夹
import os
def remove_empty_folders (directory_path ):
for root, dirs, files in os.walk(directory_path, topdown=False ):
for folder in dirs:
folder_path = os.path.join(root, folder)
if not os.listdir(folder_path):
os.rmdir(folder_path)
描述: 这个 Python 脚本搜索并删除指定目录中的空文件夹。它可以帮助你维护一个干净整洁的文件夹结构,尤其是在处理大量数据时。
1.3 重命名多个文件
import os
def rename_files (directory_path, old_name, new_name ):
for filename in os.listdir(directory_path):
if old_name in filename:
new_filename = filename.replace(old_name, new_name)
os.rename(os.path.join(directory_path, filename), os.path.join(directory_path, new_filename))
描述: 这个 Python 脚本允许你同时在目录中重命名多个文件。它接受旧名称和新名称作为输入,并为所有匹配指定条件的文件替换旧名称。
2. 使用 Python 进行网络抓取
2.1 从网站提取数据
import requests
from bs4 import BeautifulSoup
def scrape_data (url ):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser' )
描述: 这个 Python 脚本使用 requests 和 BeautifulSoup 库从网站抓取数据。它获取网页的内容并使用 BeautifulSoup 解析 HTML。你可以自定义脚本以提取特定数据,如头条、产品信息或价格。
2.2 批量下载图片
import requests
def download_images (url, save_directory ):
response = requests.get(url)
if response.status_code == 200 :
images = response.json()
for index, image_url in enumerate (images):
image_response = requests.get(image_url)
if image_response.status_code == 200 :
with open (f"{save_directory} /image_{index} .jpg" , "wb" ) as f:
f.write(image_response.content)
描述: 这个 Python 脚本设计用于从网站批量下载图片。它假设网站提供一个返回图片 URL 数组的 JSON API。脚本然后遍历 URL 并下载图片,将它们保存到指定的目录。
2.3 自动化表单提交
import requests
def submit_form (url, form_data ):
response = requests.post(url, data=form_data)
if response.status_code == 200 :
描述: 这个 Python 脚本通过发送带有表单数据的 POST 请求来自动化网站上的表单提交。你可以通过提供 URL 和要提交的必要表单数据来自定义脚本。
3. 文本处理和操作
3.1 计算文本文件中的单词数
def count_words (file_path ):
with open (file_path, 'r' ) as f:
text = f.read()
word_count = len (text.split())
return word_count
描述: 这个 Python 脚本读取文本文件并计算其中包含的单词数。它可以用于快速分析文本文档的内容,或者跟踪写作项目中的单词计数。
3.2 查找和替换文本
def find_replace (file_path, search_text, replace_text ):
with open (file_path, 'r' ) as f:
text = f.read()
modified_text = text.replace(search_text, replace_text)
with open (file_path, 'w' ) as f:
f.write(modified_text)
描述: 这个 Python 脚本在文件中搜索特定文本并用所需文本替换它。它可以用于批量替换某些短语或在大型文本文件中纠正错误。
3.3 生成随机文本
import random
import string
def generate_random_text (length ):
letters = string.ascii_letters + string.digits + string.punctuation
random_text = '' .join(random.choice(letters) for i in range (length))
return random_text
描述: 这个 Python 脚本生成指定长度的随机文本。它可以用于测试和模拟目的,甚至可以作为创意写作的随机内容来源。
4. 邮件自动化
4.1 发送个性化邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_personalized_email (sender_email, sender_password, recipients, subject, body ):
server = smtplib.SMTP('smtp.gmail.com' , 587 )
server.starttls()
server.login(sender_email, sender_password)
for recipient_email in recipients:
message = MIMEMultipart()
message['From' ] = sender_email
message['To' ] = recipient_email
message['Subject' ] = subject
message.attach(MIMEText(body, 'plain' ))
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
描述: 这个 Python 脚本使你能够向收件人列表发送个性化邮件。你可以自定义发件人的电子邮件、密码、主题、正文和收件人电子邮件列表。请注意,出于安全原因,使用 Gmail 时应使用应用程序特定的密码。
4.2 邮件附件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_email_with_attachment (sender_email, sender_password, recipient_email, subject, body, file_path ):
server = smtplib.SMTP('smtp.gmail.com' , 587 )
server.starttls()
server.login(sender_email, sender_password)
message = MIMEMultipart()
message['From' ] = sender_email
message['To' ] = recipient_email
message['Subject' ] = subject
message.attach(MIMEText(body, 'plain' ))
with open (file_path, "rb" ) as attachment:
part = MIMEBase('application' , 'octet-stream' )
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition' , f"attachment; filename= {file_path} " )
message.attach(part)
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
描述: 这个 Python 脚本允许你发送带有文件附件的邮件。只需提供发件人的电子邮件、密码、收件人的电子邮件、主题、正文和要附加的文件的路径。
4.3 自动邮件提醒
import smtplib
from email.mime.text import MIMEText
from datetime import datetime, timedelta
def send_reminder_email (sender_email, sender_password, recipient_email, subject, body, reminder_date ):
server = smtplib.SMTP('smtp.gmail.com' , 587 )
server.starttls()
server.login(sender_email, sender_password)
now = datetime.now()
reminder_date = datetime.strptime(reminder_date, '%Y-%m-%d' )
if now.date() == reminder_date.date():
message = MIMEText(body, 'plain' )
message['From' ] = sender_email
message['To' ] = recipient_email
message['Subject' ] = subject
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
描述: 这个 Python 脚本根据指定的日期发送自动邮件提醒。它可用于设置重要任务或事件的提醒,确保你永远不会错过截止日期。
5. Excel 电子表格自动化
5.1 读取和写入 Excel
import pandas as pd
def read_excel (file_path ):
df = pd.read_excel(file_path)
return df
def write_to_excel (data, file_path ):
df = pd.DataFrame(data)
df.to_excel(file_path, index=False )
描述: 这个 Python 脚本使用 pandas 库从 Excel 电子表格读取数据并将数据写入新的 Excel 文件。它允许你以编程方式处理 Excel 文件,使数据操作和分析更加高效。
5.2 数据分析和可视化
import pandas as pd
import matplotlib.pyplot as plt
def analyze_and_visualize_data (data ):
pass
描述: 这个 Python 脚本使用 pandas 和 matplotlib 库进行数据分析和可视化。它使你能够探索数据集,获取洞察力,并创建数据的可视化表示。
5.3 合并多个表格
import pandas as pd
def merge_spreadsheets (file_paths, output_file_path ):
all_data = []
for file_path in file_paths:
df = pd.read_excel(file_path)
all_data.append(df)
merged_data = pd.concat(all_data, ignore_index=True )
merged_data.to_excel(output_file_path, index=False )
描述: 这个 Python 脚本合并多个 Excel 电子表格到一个单一的文件。它读取每个文件的数据,然后将所有数据合并到一个数据框中,并将结果保存到新的 Excel 文件。
6. 与数据库交互
6.1 连接到数据库
import sqlite3
def connect_to_database (database_path ):
connection = sqlite3.connect(database_path)
cursor = connection.cursor()
return cursor
def execute_query (cursor, query ):
cursor.execute(query)
results = cursor.fetchall()
return results
描述: 这个 Python 脚本连接到 SQLite 数据库并执行查询。它使你能够以编程方式与数据库交互,从而更有效地管理和查询数据。
6.2 数据库备份
import shutil
def backup_database (database_path, backup_path ):
shutil.copy(database_path, backup_path)
描述: 这个 Python 脚本备份数据库文件到指定的路径。它确保你的数据始终安全,并允许你在需要时恢复数据。
6.3 数据库迁移
import sqlite3
def migrate_data (source_database, target_database ):
source_connection = sqlite3.connect(source_database)
target_connection = sqlite3.connect(target_database)
source_cursor = source_connection.cursor()
target_cursor = target_connection.cursor()
source_connection.close()
target_connection.close()
描述: 这个 Python 脚本迁移数据从一个数据库到另一个数据库。它可以用于数据整合、备份或迁移项目。
7. 社交媒体自动化
import tweepy
def post_to_twitter (consumer_key, consumer_secret, access_token, access_token_secret, tweet_text ):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
api.update_status(status=tweet_text)
描述: 这个 Python 脚本使用 tweepy 库自动发布推文到 Twitter。你只需提供 API KEY、访问令牌和要发布的推文文本。
7.2 自动发布到 Instagram
from instabot import Bot
def post_to_instagram (username, password, image_path, caption ):
bot = Bot()
bot.login(username=username, password=password)
bot.upload_photo(image_path, caption=caption)
描述: 这个 Python 脚本使用 instabot 库自动发布图片到 Instagram。你只需提供 Instagram 的用户名、密码、图片路径和标题。
7.3 自动发布到 Facebook
import facebook
def post_to_facebook (access_token, message ):
graph = facebook.GraphAPI(access_token)
graph.put_object(parent_object='me' , connection_name='feed' , message=message)
描述: 这个 Python 脚本使用 facebook-sdk 库自动发布状态到 Facebook。你只需提供访问令牌和要发布的消息。
8. 系统任务自动化
8.1 自动关机计算机
import os
def shutdown_computer ():
os.system("shutdown /s /t 1" )
描述: 这个 Python 脚本自动关机计算机。它可以用于在完成特定任务后自动关闭计算机,或者在指定的时间关闭计算机。
8.2 自动备份文件
import shutil
def backup_files (source_directory, backup_directory ):
shutil.copytree(source_directory, backup_directory)
描述: 这个 Python 脚本自动备份指定目录中的所有文件到备份目录。它确保你的文件始终安全,并允许你在需要时恢复数据。
8.3 自动更新软件
import os
def update_software ():
os.system("sudo apt-get update && sudo apt-get upgrade" )
描述: 这个 Python 脚本自动更新 Linux 系统上的所有软件。它确保你的系统始终是最新的,并提供了最新的安全性和功能更新。
9. 图像编辑自动化
9.1 批量重命名图片
import os
def rename_images (directory_path, prefix ):
for index, filename in enumerate (os.listdir(directory_path)):
if filename.endswith(('.jpg' , '.jpeg' , '.png' )):
new_filename = f"{prefix} _{index} .jpg"
os.rename(os.path.join(directory_path, filename), os.path.join(directory_path, new_filename))
描述: 这个 Python 脚本批量重命名目录中的图片。它为每个图片文件添加一个前缀,并按顺序编号。
9.2 批量调整图片大小
from PIL import Image
import os
def resize_images (directory_path, width, height ):
for filename in os.listdir(directory_path):
if filename.endswith(('.jpg' , '.jpeg' , '.png' )):
image_path = os.path.join(directory_path, filename)
img = Image.open (image_path)
img = img.resize((width, height))
img.save(image_path)
描述: 这个 Python 脚本批量调整目录中的图片大小。它为每个图片文件设置新的宽度和高度,并保存修改后的图片。
9.3 批量转换图片格式
from PIL import Image
import os
def convert_images (directory_path, output_format ):
for filename in os.listdir(directory_path):
if filename.endswith(('.jpg' , '.jpeg' , '.png' )):
image_path = os.path.join(directory_path, filename)
img = Image.open (image_path)
new_filename = os.path.splitext(filename)[0 ] + f".{output_format} "
img.save(os.path.join(directory_path, new_filename))
描述: 这个 Python 脚本批量转换目录中的图片格式。它为每个图片文件设置新的文件格式,并保存修改后的图片。
10. 网络自动化
10.1 自动连接到 VPN
import os
def connect_to_vpn (vpn_name ):
os.system(f"rasdial {vpn_name} " )
描述: 这个 Python 脚本自动连接到 VPN。它使用 Windows 的 rasdial 命令连接到指定的 VPN 名称。
10.2 自动检测网络连接
import os
def check_network_connection ():
response = os.system("ping -c 1 google.com" )
if response == 0 :
return True
else :
return False
描述: 这个 Python 脚本自动检测网络连接。它使用 ping 命令检查是否可以访问。如果可以访问,则返回 True,否则返回 False。
10.3 自动下载文件
import requests
def download_file (url, save_path ):
response = requests.get(url)
with open (save_path, 'wb' ) as f:
f.write(response.content)
描述: 这个 Python 脚本自动从 URL 下载文件。它使用 requests 库获取文件内容,并将其保存到指定的路径。
11. 数据清理和转换
11.1 清理 CSV 文件
import pandas as pd
def clean_csv (file_path ):
df = pd.read_csv(file_path)
df.to_csv(file_path, index=False )
描述: 这个 Python 脚本清理 CSV 文件中的数据。它使用 pandas 库读取文件内容,然后你可以添加自定义的数据清理代码。
11.2 转换 CSV 到 JSON
import pandas as pd
def csv_to_json (csv_file_path, json_file_path ):
df = pd.read_csv(csv_file_path)
df.to_json(json_file_path, orient='records' )
描述: 这个 Python 脚本将 CSV 文件转换为 JSON 格式。它使用 pandas 库读取 CSV 文件内容,然后将数据保存为 JSON 文件。
11.3 转换 JSON 到 CSV
import pandas as pd
def json_to_csv (json_file_path, csv_file_path ):
df = pd.read_json(json_file_path)
df.to_csv(csv_file_path, index=False )
描述: 这个 Python 脚本将 JSON 文件转换为 CSV 格式。它使用 pandas 库读取 JSON 文件内容,然后将数据保存为 CSV 文件。
12. PDF 操作自动化
12.1 合并多个 PDF 文件
from PyPDF2 import PdfFileReader, PdfFileWriter
def merge_pdfs (pdf_file_paths, output_file_path ):
pdf_writer = PdfFileWriter()
for pdf_file_path in pdf_file_paths:
pdf_reader = PdfFileReader(pdf_file_path)
for page_num in range (pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
pdf_writer.addPage(page)
with open (output_file_path, 'wb' ) as f:
pdf_writer.write(f)
描述: 这个 Python 脚本合并多个 PDF 文件到一个单一的文件。它使用 PyPDF2 库读取每个 PDF 文件的内容,并将所有页面合并到一个新的 PDF 文件。
12.2 提取 PDF 文本
from PyPDF2 import PdfFileReader
def extract_text_from_pdf (pdf_file_path ):
pdf_reader = PdfFileReader(pdf_file_path)
text = ""
for page_num in range (pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
text += page.extractText()
return text
描述: 这个 Python 脚本从 PDF 文件提取文本。它使用 PyPDF2 库读取 PDF 文件的内容,并返回所有页面的文本。
12.3 加密 PDF 文件
from PyPDF2 import PdfFileReader, PdfFileWriter
def encrypt_pdf (pdf_file_path, output_file_path, password ):
pdf_reader = PdfFileReader(pdf_file_path)
pdf_writer = PdfFileWriter()
for page_num in range (pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
pdf_writer.addPage(page)
pdf_writer.encrypt(password)
with open (output_file_path, 'wb' ) as f:
pdf_writer.write(f)
描述: 这个 Python 脚本加密 PDF 文件。它使用 PyPDF2 库读取 PDF 文件的内容,然后使用指定的密码加密文件,并保存加密后的 PDF 文件。
13. GUI 自动化
13.1 自动点击屏幕
import pyautogui
def click_screen (x, y ):
pyautogui.click(x, y)
描述: 这个 Python 脚本自动点击屏幕上的指定坐标。它使用 pyautogui 库模拟鼠标点击。
13.2 自动填写表单
import pyautogui
def fill_form (fields ):
for field in fields:
pyautogui.click(field['x' ], field['y' ])
pyautogui.write(field['text' ])
描述: 这个 Python 脚本自动填写屏幕上的表单。它使用 pyautogui 库模拟鼠标点击和键盘输入。你可以为每个字段提供坐标和要输入的文本。
13.3 自动截屏
import pyautogui
def screenshot_region (x, y, width, height, save_path ):
screenshot = pyautogui.screenshot(region=(x, y, width, height))
screenshot.save(save_path)
描述: 这个 Python 脚本自动截取屏幕上的指定区域。它使用 pyautogui 库获取屏幕截图,并将其保存到指定的路径。
14. 测试自动化
14.1 自动化网站测试
from selenium import webdriver
def test_website (url ):
driver = webdriver.Chrome()
driver.get(url)
driver.quit()
描述: 这个 Python 脚本自动化网站测试。它使用 selenium 库打开网站,并允许你添加自定义的自动化测试代码。
14.2 自动化 API 测试
import requests
def test_api (api_url, method, headers, data ):
if method == 'GET' :
response = requests.get(api_url, headers=headers)
elif method == 'POST' :
response = requests.post(api_url, headers=headers, data=data)
return response
描述: 这个 Python 脚本自动化 API 测试。它使用 requests 库发送 API 请求,并允许你添加自定义的 API 测试代码。
14.3 自动化 UI 测试
from selenium import webdriver
def test_ui (ui_elements ):
driver = webdriver.Chrome()
for element in ui_elements:
driver.find_element_by_id(element['id' ]).click()
driver.quit()
描述: 这个 Python 脚本自动化 UI 测试。它使用 selenium 库模拟用户与 UI 元素的交互,并允许你添加自定义的 UI 测试代码。
15. 云服务自动化
15.1 自动上传文件到 Google Drive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
def upload_to_google_drive (file_path ):
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
file = drive.CreateFile()
file.SetContentFile(file_path)
file.Upload()
描述: 这个 Python 脚本自动上传文件到 Google Drive。它使用 pydrive 库进行身份验证,并将文件上传到你的 Google Drive 帐户。
15.2 自动下载文件从 Amazon S3
import boto3
def download_from_s3 (bucket_name, file_key, save_path ):
s3 = boto3.client('s3' )
s3.download_file(bucket_name, file_key, save_path)
描述: 这个 Python 脚本自动从 Amazon S3 下载文件。它使用 boto3 库连接到 S3,并从指定的存储桶下载文件。
15.3 自动备份数据库到 Azure Blob Storage
from azure.storage.blob import BlobServiceClient
def backup_to_azure_blob (connection_string, container_name, database_path, blob_name ):
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
with open (database_path, "rb" ) as f:
blob_client.upload_blob(f)
描述: 这个 Python 脚本自动备份数据库到 Azure Blob Storage。它使用 azure.storage.blob 库连接到 Azure Blob Storage,并将数据库文件上传到指定的容器。
16. 财务自动化
16.1 自动化股票数据获取
import yfinance as yf
def get_stock_data (ticker_symbol, start_date, end_date ):
stock = yf.Ticker(ticker_symbol)
data = stock.history(start=start_date, end=end_date)
return data
描述: 这个 Python 脚本自动化获取股票数据。它使用 yfinance 库从 Yahoo Finance 获取指定日期范围内的股票数据。
16.2 自动化发票生成
from fpdf import FPDF
def generate_invoice (client_name, items, total_amount, save_path ):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial" , size=12 )
pdf.cell(200 , 10 , txt=f"Invoice for {client_name} " , ln=True , align='C' )
for item in items:
pdf.cell(200 , 10 , txt=item, ln=True )
pdf.cell(200 , 10 , txt=f"Total Amount: ${total_amount} " , ln=True , align='R' )
pdf.output(save_path)
描述: 这个 Python 脚本自动化生成发票。它使用 fpdf 库创建 PDF 发票,并将其保存到指定的路径。
16.3 自动化预算跟踪
import pandas as pd
def track_budget (expenses, budget ):
total_expenses = sum (expenses)
remaining_budget = budget - total_expenses
return remaining_budget
描述: 这个 Python 脚本自动化跟踪预算。它计算总支出,并返回剩余的预算金额。
17. 机器学习自动化
17.1 自动化数据预处理
import pandas as pd
from sklearn.preprocessing import StandardScaler
def preprocess_data (data ):
scaler = StandardScaler()
scaled_data = scaler.fit_transform(data)
return scaled_data
描述: 这个 Python 脚本自动化数据预处理。它使用 sklearn 库标准化数据,使其具有零均值和单位方差。
17.2 自动化模型训练
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
def train_model (data, target ):
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2 )
model = LinearRegression()
model.fit(X_train, y_train)
return model
描述: 这个 Python 脚本自动化模型训练。它使用 sklearn 库分割数据并训练线性回归模型。
17.3 自动化模型评估
from sklearn.metrics import mean_squared_error
def evaluate_model (model, X_test, y_test ):
predictions = model.predict(X_test)
mse = mean_squared_error(y_test, predictions)
return mse
描述: 这个 Python 脚本自动化模型评估。它使用 sklearn 库计算模型的均方误差。
18. 音频和视频自动化
18.1 自动化音频转换
from pydub import AudioSegment
def convert_audio (input_file, output_format ):
audio = AudioSegment.from_file(input_file)
output_file = input_file.split('.' )[0 ] + f".{output_format} "
audio.export(output_file, format =output_format)
描述: 这个 Python 脚本自动化转换音频格式。它使用 pydub 库读取音频文件,并将其保存为指定的格式。
18.2 自动化视频剪辑
from moviepy.editor import VideoFileClip
def clip_video (input_file, start_time, end_time, output_file ):
video = VideoFileClip(input_file)
clipped_video = video.subclip(start_time, end_time)
clipped_video.write_videofile(output_file)
描述: 这个 Python 脚本自动化剪辑视频。它使用 moviepy 库读取视频文件,并将指定的时间段保存为新的视频文件。
18.3 自动化视频转换
from moviepy.editor import VideoFileClip
def convert_video (input_file, output_format ):
video = VideoFileClip(input_file)
output_file = input_file.split('.' )[0 ] + f".{output_format} "
video.write_videofile(output_file)
描述: 这个 Python 脚本自动化转换视频格式。它使用 moviepy 库读取视频文件,并将其保存为指定的格式。
19. 游戏自动化
19.1 自动化游戏玩家输入
import pyautogui
def simulate_game_input (keys ):
for key in keys:
pyautogui.press(key)
描述: 这个 Python 脚本自动化模拟游戏玩家输入。它使用 pyautogui 库模拟键盘按键。
19.2 自动化游戏测试
import time
def test_game_performance (game_function ):
start_time = time.time()
game_function()
end_time = time.time()
performance_time = end_time - start_time
return performance_time
描述: 这个 Python 脚本自动化测试游戏性能。它计算运行游戏函数所需的时间,并返回性能时间。
19.3 自动化游戏更新
import os
def update_game (update_url, save_path ):
response = requests.get(update_url)
with open (save_path, 'wb' ) as f:
f.write(response.content)
os.system(f"install {save_path} " )
描述: 这个 Python 脚本自动化下载和安装游戏更新。它从指定的 URL 下载更新,并使用系统命令安装更新。
20. 安全性自动化
20.1 自动化密码生成器
import random
import string
def generate_password (length ):
characters = string.ascii_letters + string.digits + string.punctuation
password = '' .join(random.choice(characters) for i in range (length))
return password
描述: 这个 Python 脚本自动化生成随机密码。它使用 random 和 string 库生成指定长度的随机字符组合。
20.2 自动化文件加密
from cryptography.fernet import Fernet
def encrypt_file (file_path, key ):
cipher = Fernet(key)
with open (file_path, 'rb' ) as f:
file_data = f.read()
encrypted_data = cipher.encrypt(file_data)
with open (file_path, 'wb' ) as f:
f.write(encrypted_data)
描述: 这个 Python 脚本自动化加密文件。它使用 cryptography 库加密文件内容,并将加密后的数据保存回文件。
20.3 自动化文件解密
from cryptography.fernet import Fernet
def decrypt_file (file_path, key ):
cipher = Fernet(key)
with open (file_path, 'rb' ) as f:
encrypted_data = f.read()
decrypted_data = cipher.decrypt(encrypted_data)
with open (file_path, 'wb' ) as f:
f.write(decrypted_data)
描述: 这个 Python 脚本自动化解密文件。它使用 cryptography 库解密文件内容,并将解密后的数据保存回文件。
相关免费在线工具 RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
随机西班牙地址生成器 随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online