21. 使用 cryptography 自动化文件加密
Python 的 cryptography 库提供了一种安全的方式,使用对称加密算法对文件进行加密和解密。你可以自动化加密和解密文件的过程来保护敏感数据。
示例:文件加密和解密
假设你想使用对称加密算法加密一个文件,然后解密它。下面是使用 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 密码器。使用 open()
以二进制模式(‘rb’)读取要加密的文件内容。然后,使用 Fernet 密码器的 encrypt()
方法对数据进行加密。加密后的数据使用 open()
以二进制写入模式(‘wb’)写入了一个名为 ‘encrypted_file.txt’ 的新文件。要解密文件,它从 ‘encrypted_file.txt’ 中读取加密数据,然后使用 Fernet 密码器的 decrypt()
方法对其进行解密。解密后的数据然后写入名为 ‘decrypted_file.txt’ 的新文件。最后,它打印出成功加密和解密文件的消息。
22. 使用 gzip 自动化文件压缩
Python 的 gzip 模块允许你使用 gzip 压缩算法对文件进行压缩和解压缩。你可以自动化压缩文件的过程以节省存储空间并减少文件传输时间。
示例:压缩和解压文件
假设你想使用 gzip 压缩一个文件,然后解压它。下面是使用 Python 自动化此任务的方法:
import gzip
# 要压缩的文件
file_to_compress = 'example.txt'
# 压缩文件
with open(file_to_compress,