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

os.scandir抛出NotADirectoryError异常问题排查

问题:遍历文件夹时触发NotADirectoryError错误

我在编写文件夹遍历函数时遇到问题,代码如下:

import os
from pathlib import Path


path = Path(r'D:\full')
for i in os.scandir(path):#folders
     for j in os.scandir(i.path):#subdict
          for k in os.scandir(j.path):#files
               print(k.path)

程序处理名为12.288.csv的文件时停止运行,抛出错误:

Traceback (most recent call last):
  File "D:\project\MOTOR.py", line 7, in <module>
    for k in os.scandir(j.path):#files
NotADirectoryError: [WinError 267] The directory name is invalid: 'D:\\full\\normal\\12.288.csv'

该文件路径实际存在,但我尝试以下方法后仍未解决:

  • 使用双斜杠路径
  • 用原始字符串定义路径
  • 检查目录是否存在
  • 切换正斜杠与反斜杠

请问问题出在哪里?


解决方案

问题本质很明确:你对文件路径调用了os.scandir(),但这个函数只能接收目录路径作为参数。

你的代码默认i、j都是目录,但实际j可能是文件(比如这个12.288.csv),当你试图扫描一个文件时,自然会抛出NotADirectoryError。

修正方法是每次调用os.scandir()前,先判断当前条目是否为目录:

import os
from pathlib import Path

path = Path(r'D:\full')
for i in os.scandir(path):
    if i.is_dir():  # 确认是目录才继续遍历
        for j in os.scandir(i.path):
            if j.is_dir():  # 再次确认是目录
                for k in os.scandir(j.path):
                    print(k.path)

如果需求是遍历所有层级的文件,更简洁的方式是用pathlib的rglob方法:

from pathlib import Path

path = Path(r'D:\full')
for file_path in path.rglob('*'):
    if file_path.is_file():  # 仅打印文件路径
        print(file_path)

或者用os.walk,它会自动区分目录与文件:

import os

for root, dirs, files in os.walk(r'D:\full'):
    for file in files:
        print(os.path.join(root, file))

内容的提问来源于stack exchange,提问作者TheHappyBee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:23:17