如何加密目录中的嵌套文件夹

How to encrypt nested folders inside a directory

我正在尝试制作一个可以加密目录的程序。不过,我目前所拥有的只能加密目录内的文件,而不能加密嵌套的文件夹。一个例子是如果你想加密“图片”文件夹,它也会加密“保存的图片”和“相机胶卷”以及“图片”中的文件。任何帮助将不胜感激

from cryptography.fernet import Fernet
import os

'''
def write_key():
    key = Fernet.generate_key()
    with open('key.key', "wb") as key_file:
        key_file.write(key)
'''


def load_key():
    file = open('key.key', 'rb')
    key_ = file.read()
    file.close()
    return key_


key = load_key()
fer = Fernet(key)

os.chdir(r"C:\Users\{user}\encrypt_test".format(user=os.getlogin()))
files = os.listdir()
print(files)

for i in range(len(files)):

    with open(files[i], 'rb') as f:
        data = f.read()

    with open(files[i], 'w') as f:
        print(len(data))
        f.write(fer.encrypt(data).decode())
        print('done')






您要求做的是递归地遍历目录以查找所有文件并对其应用一些操作。 os.listdir method as you've seen only gives you the entries in the immediate directory. While you could use that method to write a recursive method (e.g. check if a given entry is a directory, if so, run os.listdir over it, else encrypt, repeat), it's must easier to use os.walk 将为您处理文件树的递归,以及将文件与每个级别的目录分开。这里要注意的一件事是 files 数组, os.walk returns 只是该级别文件的名称,因此您需要将它与 root 组合起来获取完整路径的值。

重写代码以使用呈现:

from cryptography.fernet import Fernet
import os
import path

'''
def write_key():
    key = Fernet.generate_key()
    with open('key.key', "wb") as key_file:
        key_file.write(key)
'''


def load_key():
    file = open('key.key', 'rb')
    key_ = file.read()
    file.close()
    return key_


key = load_key()
fer = Fernet(key)

os.chdir(r"C:\Users\{user}\encrypt_test".format(user=os.getlogin()))

for root, dirs, files in os.walk('.'):
    print(files)
    for filename in files:
        filepath = path.join(root, filename)

        with open(filepath, 'rb') as f:
            data = f.read()

        with open(filepath, 'w') as f:
            print(len(data))
            f.write(fer.encrypt(data).decode())
            print('done')