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
相关产品推荐
相关产品推荐

