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

Python os.path.isdir()无法识别嵌套文件夹问题应如何解决

问题根因

你调用os.listdir(folder)返回的仅为子文件/子文件夹的纯名称,不是完整路径。直接把纯名称传给os.path.isdir()时,系统会默认在当前运行脚本的工作目录下查找对应路径,而非你正在遍历的folder目录下查找,因此嵌套层级的子文件夹无法被正确识别。

需要修改的两处内容
  • 路径类型判断前,先拼接当前遍历目录folder和拿到的名称file,得到完整路径full_path = os.path.join(folder, file),用完整路径做文件夹判断
  • 子文件夹加入遍历队列folders时,不能直接加纯名称file,要添加拼接后的完整路径full_path,否则后续遍历子目录时同样会因为路径错误出现异常
修正后可运行的完整代码
import openpyxl
import os


def add_row(rowN, folderName, fileName, ext):
    sheet.cell(row=rowN, column=1).value = rowN
    sheet.cell(row=rowN, column=2).value = folderName
    sheet.cell(row=rowN, column=3).value = fileName
    sheet.cell(row=rowN, column=4).value = ext

path = os.path.abspath(os.getcwd())
folders = []
i = 0
wb = openpyxl.Workbook()
sheet = wb.active
sheet['A1'] = 'Number of row'
sheet['B1'] = 'Folder where file located'
sheet['C1'] = 'File name'
sheet['D1'] = 'File extension'

folders.append(path)

for folder in folders:
    try:
        for file in os.listdir(folder):
            # 拼接得到完整路径
            full_path = os.path.join(folder, file)
            if not os.path.isdir(full_path):
                i = i + 1
                add_row(i, os.path.basename(folder), os.path.splitext(file)[0], 
        os.path.splitext(file)[1])
            else:
                # 加入完整路径到遍历队列
                folders.append(full_path)

    except:
        print(folders)
wb.save("test.xlsx")
wb.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:06:08