我想要一个针对 linux 中的 maxdepth
选项的标准 python 解决方案。我可以用 os.walk()
模拟 find
命令,但我想限制代码级别的深度。我不想在我的代码中使用 subprocess
或 Popen
。
最佳答案
您可以递归地遍历所有路径,直到达到一定深度。此解决方案不是特别有效,但它应该可以帮助您入门(需要 Python 3.3 或更高版本):
def find(path, maxdepth=-1, depth=0):
path = "%s/" % path if path[-1] != "/" else path
for f in os.listdir(path):
p = "%s%s" % (path, f)
yield p
try:
if (depth < maxdepth or maxdepth == -1) and os.path.isdir(p):
yield from find(p, maxdepth, depth + 1)
except OSError:
pass
用法:
find(path, maxdepth)
# maxdepth=-1 means infinite depth (default)
关于python - 如何将linux的find命令的 `maxdepth`选项模拟到python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43654654/