首页 > 解决方案 > 遍历目录,直到找到特定的文件夹名称

问题描述

我想通过一个目录向下走几层,直到找到一个以整数命名的文件夹,然后对文件夹内的东西进行某些操作。重要的是我仍然可以访问已处理文件夹的名称(整数),因为我使用它来命名操作的输出。我需要的文件夹名称中始终只有一个整数,没有其他字符。我尝试了一个有效的嵌套循环,但不幸的是我并不总是具有相同的深度(有时它会下降 2 个文件夹,有时会更多)

这是我到目前为止所得到的,它似乎适用于某些目录,但在其他目录上没有返回任何内容。

for root, dirs, files in os.walk("directory"):
    for name in dirs:
        try:
            int(name.split("\\")[-1])
            print(os.path.join(root, name))
        except:
            continue

可能会更好的是,循环在到达包含具有整数名称的文件夹的文件夹时立即停止,然后对这些整数子文件夹执行某些操作。

这样做最有效的方法是什么?

标签: pythonloopssearchdirectory

解决方案


你的代码很好。我只做了一些小的改动,让它更通用一点。让我知道什么不起作用,例如丢失的目录路径,我会改进我的答案。

import os

def process_folders(root_dn, f, op):
    processed = []
    for root, dirs, files in os.walk(root_dn):
        for dn in dirs:
            if f(dn):
                path = os.path.join(root, dn)
                rv = op(dn, path)
                processed += [(dn, path, rv)]

    return processed

# This is the function that tests if the directory name is one you're looking for
def dn_filter(s):
    rv = True
    try:
        int(s)
    except:
        rv = False
    return rv
    # -or-
    #return s in in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

# This is the function that will process your directory. Return a value to indicate success
def dn_op(dn, path):
    print('Processing:', dn, 'at', path)
    return True

root_dn = '.'
processed = process_folders(root_dn, dn_filter, dn_op)
# Print all processed directories and their associated return values
for dn, path, success in processed:
    print(dn, path, success)

推荐阅读