出现错误时如何使此循环继续?

时间:2018-08-03 19:09:46

标签: python python-3.x loops exception-handling

def encryption_process(startpath=None):
    for filename in glob.iglob(os.path.join(startpath, '**'), recursive=True):
        if(os.path.isfile(filename)):
            print('Encrypting> ' + filename)
            encrypt_file(key, filename)
            os.remove(filename)

有时我会从中得到Windows权限错误,有没有办法让我在出现错误时继续显示列表,而只跳过给出错误的文件?

1 个答案:

答案 0 :(得分:1)

首先阅读官方文档中的"Handling Exceptions"部分。

您正在寻找有问题的代码周围的try块:

try:
    print('Encrypting>', filename)
    encrypt_file(key, filename)
except OSError as e:
    print('Failed due to', str(e))
else:
    os.remove(filename)

如果encrypt_file不允许使用目录(即引发错误),则可以删除封闭的if os.path.isfile(filename):。相反,也要捕获该错误,因为try可以包含任意数量的except个块:

try:
    print('Encrypting>', filename)
    encrypt_file(key, filename)
except OSError as e:
    print('Failed due to', str(e))
except SomeOtherError:
    print('Failed:', filename, 'is a directory!')
else:
    os.remove(filename)