给定文件路径时查找最高深度

Find highest depth when given a file path

假设我有一个如下图所示的文件树。

我有一个函数可以通过用户输入的文件路径。我希望函数在该路径中找到最高深度。例如在上图中,文件夹 'test' 的最高深度是 3,因为它包含 folder1,其中包含 folder11,其中包含 fileD.txt。

我的代码:

def depth(path, depth_count=0):
    for item in os.listdir(path):
        try:
            newItem = os.path.join(path, item)
            print(newItem)
            if isdir(newItem):
                depth_count += 1
            print('Depth is currently: ' + str(depth_count))
            depth(newItem, depth_count)
        except:
            pass
    return 'Highest depth is ' + str(depth_count)

我把这个输入 shell:

depth('C:\Users\John\Documents\test')

结果是这样的:

C:\Users\John\Documents\test\fileA.txt
Depth is currently: 0
C:\Users\John\Documents\test\folder1
Depth is currently: 1
C:\Users\John\Documents\test\folder1\fileB.txt
Depth is currently: 1
C:\Users\John\Documents\test\folder1\fileC.txt
Depth is currently: 1
C:\Users\John\Documents\test\folder1\folder11
Depth is currently: 2
C:\Users\John\Documents\test\folder1\folder11\fileD.txt
Depth is currently: 2
C:\Users\John\Documents\test\folder2
Depth is currently: 2
C:\Users\John\Documents\test\folder2\fileD.txt
Depth is currently: 2
C:\Users\John\Documents\test\folder2\fileE.txt
Depth is currently: 2
'Highest depth is 2'

问题是最高深度应该是三个而不是两个。还有,这个函数需要用到递归,不能用os.walk.

import os

def get_depth(path='.', depth=0):
    for root, dirs, files in os.walk(path):
        if dirs or files:
            depth += 1
        if dirs:
            return max(get_depth(os.path.join(root, d), depth) for d in dirs)
    # Will return 0 for an empty directory
    return depth

你可以做一个"depth first search"

def get_depth(path, depth=0):
    if not os.path.isdir(path): return depth
    maxdepth = depth
    for entry in os.listdir(path):
        fullpath = os.path.join(path, entry)
        maxdepth = max(maxdepth, get_depth(fullpath, depth + 1))
    return maxdepth

这是您的解决方案的一般方法,但我认为您忘记计算常规文件的深度比它们所在的目录大 1。