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权限错误,有没有办法让我在出现错误时继续显示列表,而只跳过给出错误的文件?
答案 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)