要使用Python给文件夹加密码,你可以使用`cryptography`库中的`Fernet`类进行加密和解密操作。以下是一个简单的示例,展示如何加密和解密文件夹中的所有文件:
from cryptography.fernet import Fernet
import os
def encrypt_folder(path, key):
f = Fernet(key)
for root, _, files in os.walk(path):
for file in files:
filepath = os.path.join(root, file)
with open(filepath, 'rb') as f1:
data = f1.read()
encrypted_data = f.encrypt(data)
with open(filepath, 'wb') as f1:
f1.write(encrypted_data)
def decrypt_folder(path, key):
f = Fernet(key)
for root, _, files in os.walk(path):
for file in files:
filepath = os.path.join(root, file)
with open(filepath, 'rb') as f1:
encrypted_data = f1.read()
decrypted_data = f.decrypt(encrypted_data)
with open(filepath, 'wb') as f1:
f1.write(decrypted_data)
生成密钥
key = Fernet.generate_key()
加密文件夹
encrypt_folder('path_to_your_folder', key)
解密文件夹
decrypt_folder('path_to_your_folder', key)
请确保替换`path_to_your_folder`为你要加密或解密的文件夹路径,并且在使用密钥进行加密和解密时要确保密钥的安全。