如何确定我在 Python 中给定目录树的最后一个文件夹中?

How do I determine I am down in the last folder of the given directory tree in Python?

我想一直向下解析给定的目录树并在最后一个文件夹停止并检查最后一个文件夹中是否存在某些文件(比如 .nfo 文件)。

目录树及其子文件夹可能包含一些文件,因此检查文件夹是否有文件作为解决方案对我来说是不行的。

谢谢

我会做的是: 递归遍历目录。为您所在的深度级别设置一个计数器。每次您找到一个新目录时,该目录的深度 >= 您当前的计数器。保存新路径并设置计数器(>)。 这样你就必须 运行 遍历所有子目录一次,最后你就有了最后一个文件夹的路径。 然后检查该路径中的文件。

试试这个:

path = 'To:\Be\Set'
counter = 0

def getFile(path, counter, result):
    counterTmp = counter
    list = os.listdir(path)
    print (path)
    #print (list)
    for item in list:
        if (os.path.isdir(path +"\"+ item)):
            if (len(os.listdir(path +"\"+ item)) > 0):
                result, counter = getFile(path+"\"+item, counterTmp + 1, result)
        elif (counterTmp >= counter):
            result = path
    return result, counterTmp

def checkFiles(path, setToCheck):
    list = os.listDir(path)
    result = []
    for file in list:
        if (file in setToCheck)
            result.append(file)
    return result

path, counter = getFile(path, 0, '')
println(path)
setToCheck = set(["toBeFilled"])
println(checkFiles(path, setToCheck))