我有一个函数可以通过用户输入的文件路径。我希望函数在该路径中找到最高深度。例如在上图中,文件夹“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。
请您参考如下方法:
你可以做“深度优先搜索”
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。
