首页 > 解决方案 > 在 except 之后继续一个函数

问题描述

我有一个函数,它只是加密我在特定目录中的文件,我使用tryandexcept来避免错误,如果有,我只想让我的函数继续,而不是退出程序。

我的功能是加入一个循环遍历我的文件,读取它们,然后加密数据并将密文写入文件,但我的问题是,如果出现错误,由于某种原因(无法写入文件等)。 ) 我的程序就停止了。

如果出现错误,如何防止我的程序破坏我的程序并继续使用该功能?

加密功能:

你可以看到我试图从files函数中获取列表的长度,但它只是继续循环而不是停止。

def encrypt(self):
        for i in range(0, len(files())):
            try:
                for file in files():
                    print(file)
                    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

标签: python

解决方案


如果发生异常,您可以跳过该文件。

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'skipping file {file}. Reason: {e}')

推荐阅读