捕获FileNotFoundError并继续读取文件的实现方案求助
解决glob迭代器抛出FileNotFoundError后继续循环的问题
你的问题出在之前的包装函数只执行了一次next()调用,拿到第一个元素后就结束了,自然没法处理后面的迭代项。要实现跳过异常继续循环的效果,需要持续迭代原生成器,每次调用next()时捕获异常。
正确的异常捕获包装函数
def catch_filenotfounderror(iterator): while True: try: yield next(iterator) except FileNotFoundError: # 跳过触发异常的迭代项,继续下一次 continue except StopIteration: # 迭代器耗尽,终止循环 break
工作原理
- 用
while True循环持续从原迭代器中获取元素 - 每次调用
next()时包裹在try-except块里:- 遇到
FileNotFoundError时直接跳过,继续下一次迭代 - 遇到
StopIteration(迭代器没有更多元素时抛出)就终止循环
- 遇到
测试模拟场景
用你提供的模拟函数测试:
def hdd_disconnection_mockup(): for i in range(3): if i == 1: raise FileNotFoundError yield f"Untitled{i}.ipynb" for path in catch_filenotfounderror(hdd_disconnection_mockup()): print(path)
执行后输出符合预期:
Untitled0.ipynb Untitled2.ipynb
应用到pathlib场景
直接把glob生成器传入包装函数即可:
from pathlib import Path for path in catch_filenotfounderror(Path.cwd().glob("*.ipynb")): print(path)
内容的提问来源于stack exchange,提问作者edd313
相关产品推荐
相关产品推荐

