Python 实用脚本:图像、音频、文件加密等自动化场景
前言
编程语言的出现和演进都是为了直接或者简洁地改变工作效率。Python 的出现并非只能用于数据分析、机器学习,通过一些 Python 脚本可以大大提升日常工作和生活的效率,同时还可以绕开很多收费工具,节省成本。
本文介绍了十个基于 Python 的实用自动化脚本场景,涵盖图像编辑(合并、裁剪、水印)、音频处理(提取、合并、音量调整)、文件加解密、屏幕录制、PDF 表格提取、办公自动化(Excel/Word/PPT)、图片转 PDF、文本转语音及图片压缩。通过示例代码展示如何使用 Pillow、pydub、cryptography 等库实现效率提升,替代付费工具,适用于日常办公与数据处理需求。文章包含环境配置、代码详解及安全建议,帮助开发者快速构建自动化工作流。

编程语言的出现和演进都是为了直接或者简洁地改变工作效率。Python 的出现并非只能用于数据分析、机器学习,通过一些 Python 脚本可以大大提升日常工作和生活的效率,同时还可以绕开很多收费工具,节省成本。
本文将介绍十个实用的 Python 自动化脚本场景,涵盖图像处理、音频编辑、文件安全、办公自动化等领域。
在运行以下脚本前,请确保已安装 Python 3.x 环境,并通过 pip 安装所需的第三方库:
pip install pillow pydub cryptography opencv-python numpy keyboard camelot xlrd python-docx pptx gtts pygame
注意:pydub 需要系统级安装 ffmpeg;camelot 依赖 ghostscript。
使用自动化脚本以编程方式编辑图像,如模糊、旋转、翻转、合并等。相比臃肿的图形软件,简单的 Python 脚本即可轻松解决。
from PIL import Image, ImageDraw, ImageFilter
# 合并图像
img1 = Image.open('img101.jpg')
img2 = Image.open('img102.jpg')
combine = Image.blend(img1, img2, 0.5)
# 调整图像大小
resize = Image.open('img101.jpg')
resize = resize.resize((300, 300))
# 翻转图像
flip_image = Image.open('img101.jpg')
flip_image = flip_image.transpose(Image.FLIP_LEFT_RIGHT)
# 模糊图像
blur_image = Image.open('img101.jpg')
blur_image = blur_image.filter(ImageFilter.BLUR)
# 增强边缘(模拟阴影效果)
shadow_image = Image.open('img101.jpg')
shadow_image = shadow_image.filter(ImageFilter.EDGE_ENHANCE_MORE)
# 裁剪图片
crop_image = Image.open('img101.jpg')
crop_image = crop_image.crop((50, 50, 300, 200))
# 增加亮度
bright_image = Image.open('img101.jpg')
bright_image = bright_image.point(lambda p: p + 50)
# 添加文字
text_image = Image.open('img101.jpg').convert('RGB')
draw = ImageDraw.Draw(text_image)
draw.text((10, 10), "Hello World", fill=(255, 255, 255))
# 旋转图像
rotate_image = Image.open('img101.jpg')
rotate_image = rotate_image.rotate(90)
# 保存图像
img1.save('output_img.jpg')
提示:处理大图片时请注意内存占用,建议分批处理。
该脚本可编辑音频文件,包括提取声音、合并、播放、分割/切割等,替代付费音频软件。
from pydub import AudioSegment
from pydub.utils import mediainfo
from pydub.playback import play
# 从视频中提取声音
sound = AudioSegment.from_file("video.mp4", format="mp4")
sound.export("music.mp3", format="mp3")
# 获取媒体信息
info = mediainfo("music.wav")
print(info)
# 播放音频
play("music.mp3")
# 合并音频
sound1 = AudioSegment.from_file("music.mp3")
sound2 = AudioSegment.from_file("music.mp3")
combined = sound1 + sound2
combined.export("music_combined.mp3", format="mp3")
# 分割音频
sound = AudioSegment.from_file("music.mp3", format="mp3")
sound_1 = sound[:10000] # 前 10 秒
sound_2 = sound[10000:] # 剩余部分
sound_1.export("music_1.mp3", format="mp3")
sound_2.export("music_2.mp3", format="mp3")
# 增大或减小音量
sound = AudioSegment.from_file("music.mp3", format="mp3")
sound_volumn = sound + 10 # 增加 10dB
sound_volumn.export("music_volumn.mp3", format="mp3")
# 为音频添加静音
sound = AudioSegment.from_file("music.mp3", format="mp3")
sound_silence = sound + AudioSegment.silent(duration=1000) # 添加 1 秒静音
sound_silence.export("music_silence.mp3", format="mp3")
工作中常需限制重要文件的阅读人员,此脚本使用密码学技术对文件进行加密,无密钥无法读取。
from cryptography.fernet import Fernet
import os
# 生成密钥(仅首次运行需要,后续可保存复用)
def generate_key():
return Fernet.generate_key()
# 加密函数
def lock_file(file_name, key):
with open(file_name, 'rb') as file:
data = file.read()
f = Fernet(key)
encrypted_data = f.encrypt(data)
with open(file_name, 'wb') as file:
file.write(encrypted_data)
print("File Locked...")
# 解密函数
def unlock_file(file_name, key):
with open(file_name, 'rb') as file:
data = file.read()
f = Fernet(key)
decrypted_data = f.decrypt(data)
with open(file_name, 'wb') as file:
file.write(decrypted_data)
print("File Unlocked...")
# 示例用法
key = b'YOUR_SECRET_KEY_HERE' # 替换为实际生成的 Key
lock_file('test.txt', key)
unlock_file('test.txt', key)
安全建议:密钥应妥善保存,不要硬编码在代码中,建议使用环境变量管理。
许多录屏软件收费或带水印,Python 脚本可实现无水印免费录屏。
import pyautogui
import numpy as np
import cv2
import keyboard
def screen_recording():
while True:
# Press R to Start Recording
if keyboard.is_pressed('r'):
print("Recording Has been Started...")
capture_area = (1920, 1080)
codec = cv2.VideoWriter_fourcc(*'mp4v')
filename = "Your_Recording.mp4"
fps = 60.0
output_video = cv2.VideoWriter(filename, codec, fps, capture_area)
while True:
image = pyautogui.screenshot()
Image_frame = np.array(image)
Image_frame = cv2.cvtColor(Image_frame, cv2.COLOR_BGR2RGB)
output_video.write(Image_frame)
cv2.waitKey(1)
# Press Q button to Stop recording
if keyboard.is_pressed('q'):
print("Recording Has been Stopped...")
break
output_video.release()
cv2.destroyAllWindows()
break
if __name__ == "__main__":
screen_recording()
从 PDF 中提取表格通常较复杂,OCR 效果一般,手动重建工作量大。此脚本利用 camelot 库提取表格。
import camelot
# 读取 PDF 中的表格
table = camelot.read_pdf('test.pdf', pages='1-2', flavor='lattice')
# 获取表的总数
print("Total tables: ", table.n)
print(table[0].df)
print(table[1].df)
# 把表格导出为 CSV
table[0].to_csv('table1.csv')
table[1].to_csv('table2.csv')
# 把表格导出为 Excel
table[0].to_excel('table1.xlsx')
# Export Table to HTML
table[0].to_html('table1.html')
# 一次性提取和导出表
table.export('tables.csv', f='csv', compress=True)
使用 Python 实现 MS Office 软件自动化,解放双手处理重复性工作。
import xlrd
wb = xlrd.open_workbook('test.xlsx')
worksheet = wb.sheet_by_index(0)
# 根据行、列读取数据
print(worksheet.cell_value(0, 0))
# read whole row
print(worksheet.row_values(0))
# 读取整列
print(worksheet.col_values(1))
# 写入 Excel(xlrd 主要读,写需用 openpyxl 或 xlsxwriter,此处演示逻辑)
# worksheet.write(0, 0, 'Hello')
# wb.save('test.xlsx')
import docx
doc = docx.Document("zen_of_python.docx")
# 逐段读取
text = [p.text for p in doc.paragraphs]
print(text)
# 逐表读取
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
# 写入 Word 文档
doc.add_paragraph("Hello World")
doc.save("test.docx")
from pptx import Presentation
# 浏览幻灯片
PP = Presentation('file.pptx')
for slide in PP.slides:
for shape in slide.shapes:
if hasattr(shape, "text_frame") and shape.text_frame:
for paragraph in shape.text_frame.paragraphs:
for data in paragraph.runs:
print(data.text)
# 写入 PPT
PP = Presentation()
title_slide_layout = PP.slide_layouts[0]
slide = PP.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = "Automation Article"
PP.save('file.pptx')
将多张图像转换为单个 PDF 格式。
from PIL import Image
def images_to_pdf(filename_list, output_path):
images = []
for file in filename_list:
im = Image.open(file)
im = im.convert('RGB')
images.append(im)
if images:
images[0].save(output_path, save_all=True, append_images=images[1:])
print(f"Saved to {output_path}")
images_to_pdf(["test1.jpg", "test2.jpg", "test3.jpg"], "output.pdf")
使用谷歌文本转语音 API,将文本内容转换为人工智能机器人的声音。
from pygame import mixer
from gtts import gTTS
def main():
tts = gTTS('Like This Article', lang='zh-cn')
tts.save('output.mp3')
mixer.init()
mixer.music.load('output.mp3')
mixer.music.play()
if __name__ == "__main__":
main()
针对网站上传限制,压缩图片尺寸而不显著降低质量。
import PIL
from PIL import Image
from tkinter.filedialog import askopenfilename
fl = askopenfilename()
if fl:
img = Image.open(fl)
img.save("result.jpg", "JPEG", optimize=True, quality=10)
print("Compression complete.")
给任何图片添加自定义文本水印。
from PIL import Image, ImageFont, ImageDraw
def watermark_img(img_path, res_path, text, pos):
img = Image.open(img_path)
wm = ImageDraw.Draw(img)
col = (9, 3, 10)
wm.text(pos, text, fill=col)
img.show()
img.save(res_path)
img = 'initial.jpg'
watermark_img(img, 'result.jpg', 'Copyright', pos=(10, 10))
以上介绍了十个场景,涵盖了日常工作和生活中经常遇到的需求。大多数情况下,选择繁琐的工具甚至付费方案,最终效果未必理想。通过简单的 Python 脚本,可以彻底解决问题并提高效率。
最佳实践建议:
with 语句管理文件对象,避免资源泄露。掌握这些脚本后,可根据实际需求灵活组合,构建更强大的自动化工具链。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online