繁体   English   中英

加密文件需要太多时间才能完成的功能

[英]A function that encrypts files taking too much time to finish

我有一个程序可以在特定位置加密我的文件。 我为此构建了一个函数,它循环遍历存储我的文件的列表的长度,因此如果我有 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}')

文件功能:

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

为什么要遍历嵌套的文件?

for _ in range(0, len(files())):
    for file in files():

应该只是

for file in files():

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM