尚不完全清楚您想要做什么,但我可以提供一个示例,(我认为)做了足够多的事情,您可以弄清楚如何做您想做的事情:打印每个名为“anyname”的目录中第三个文件的路径名这恰好比顶部低两个级别:
for dirpath, dirnames, filenames in os.walk(top):
depth = os.path.relpath(dirpath, top).count(os.pathsep)
if depth == 2 and os.path.basename(dirpath) == "anyname":
print(os.path.join(dirpath, filenames[2]))
您可以通过修剪walk
甚至不查看超过 2 深的目录来提高效率:
for dirpath, dirnames, filenames in os.walk(top):
depth = os.path.relpath(dirpath, top).count(os.pathsep)
if depth == 2:
if os.path.basename(dirpath) == "anyname":
print(os.path.join(dirpath, filenames[2]))
dirnames.clear()
或者,更有效但更复杂一点,修剪所有未命名为“anyname”的深度 2 目录:
for dirpath, dirnames, filenames in os.walk(top):
depth = os.path.relpath(dirpath, top).count(os.pathsep)
if depth == 1:
dirnames[:] = ["anyname"] if "anyname" in dirnames else []
elif depth == 2:
print(os.path.join(dirpath, filenames[2]))
dirnames.clear()