首页 > 解决方案 > Python os.path.isdir() 不将文件夹视为文件夹

问题描述

我正在做“机器人”,它应该遍历文件夹的内容和文件夹内的文件夹,并在 excel 中保存格式中的文件列表。在进入位于文件夹中的文件夹之前,一切都做得很好。像fixedtest --> test --> insidetest。当我运行调试时,由于某种原因通过“if not os.path.isdir(file):”的问题,考虑到这个文件夹不是文件夹,他满足了这个条件。我是 python 和 os 库的初学者,所以可能是 idk 的东西以及它是如何工作的,但一切似乎都是正确的,而且很困惑。我应该改变什么,我该如何解决问题?

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):
           
            if not os.path.isdir(file):
                i = i + 1
                add_row(i, os.path.basename(folder), os.path.splitext(file)[0], 
    os.path.splitext(file)[1])
            else:
                folders.append(file)

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

标签: pythonos.pathpython-os

解决方案


推荐阅读