我有一个通过用户输入的文件路径的函数。我希望函数在该路径中找到最高深度。例如,在上图中,文件夹'test'的最高深度为3,因为它包含folder1,其中包含包含fileD.txt的folder11。
我的代码:
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。
答案 0 :(得分:1)
您可以进行"深度优先搜索"
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 :(得分:0)
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