41. 使用 cryptography 库自动化文件加密
Python 的 cryptography 库提供了一种使用对称加密算法加密和解密文件的安全方式。你可以自动化加密和解密文件的过程,以保护敏感数据。
示例:使用 Fernet 加密和解密文件
假设你想使用 Fernet 对称加密算法加密一个文件,然后再解密它。以下是如何使用 cryptography 库自动化此任务的方法:
from cryptography.fernet import Fernet
# 要加密的文件
file_to_encrypt = 'sensitive_data.txt'
# 生成一个密钥
key = Fernet.generate_key()
# 使用该密钥创建一个 Fernet 密码器
cipher = Fernet(key)
# 读取文件内容
with open(file_to_encrypt, 'rb') as file:
data = file.read()
# 加密数据
encrypted_data = cipher.encrypt(data)
# 将加密数据写入新文件
with open('encrypted_file.txt', 'wb') as file:
file.write(encrypted_data)
print("文件成功加密。")
# 解密文件
with open('encrypted_file.txt', 'rb') as file:
encrypted_data = file.read()
decrypted_data = cipher.decrypt(encrypted_data)
# 将解密数据写入新文件
with open('decrypted_file.txt', 'wb') as file:
file.write(decrypted_data)
print("文件成功解密。")
这段代码片段使用 Fernet.generate_key()
生成一个随机加密密钥。然后,它使用生成的密钥创建一个 Fernet 密码器。它以二进制模式 (‘rb’) 使用 open()
读取要加密的文件的内容。然后使用 Fernet 密码器的 encrypt()
方法加密数据。加密的数据使用二进制写模式 (‘wb’) 的 open()
写入名为 ‘encrypted_file.txt’ 的新文件中。为了解密文件,它从 ‘encrypted_file.txt’ 读取加密数据,并使用 Fernet 密码器的 decrypt()
方法解密。解密的数据随后被写入名为 ‘decrypted_file.txt’ 的新文件中。最后,它打印出成功加密和解密文件的消息。
42. 使用 Pillow 自动化图片水印处理
Python 的 Pillow 库提供了图像处理功能,包括向图像添加水印。你可以自动化为多张图片添加特定文本或标志的水印的过程。
示例:向图片添加文本水印
假设你想为一批图片添加文本水印。以下是如何使用 Pillow 库自动化此任务的方法:
from PIL import Image, ImageDraw, ImageFont
import os
# 包含图片的目录
image_directory = 'path/to/image/directory'
# 水印文本和字体
watermark_text = 'Your Watermark'
font = ImageFont.truetype('arial.ttf', 36)
# 遍历目录中的图片
for filename in os.listdir(image_directory):
if filename.endswith('.jpg') or filename.endswith('.png'):
# 打开图片
image_path = os.path.join(image_directory, filename)
image = Image.open(image_path)
# 创建绘图上下文
draw = ImageDraw.Draw(image)
# 计算水印位置
text_width, text_height = draw.textsize(watermark_text, font)
x = image.width - text_width - 10
y = image.height - text_height - 10
# 在图片上绘制水印
draw.text((x, y), watermark_text, font=font, fill=(255, 255, 255