You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

捕获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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:15:30