os.walk 一次 python 的干净方式

clean way to os.walk once python

我想一次谈几个目录,只抓取一个目录的信息。目前我使用:

i = 0
for root, dirs, files in os.walk(home_path):
    if i >= 1:
        return 1
    i += 1
    for this_dir in dirs:
       do stuff

这当然非常乏味。当我想遍历其下的子目录时,我使用 j 等执行相同的 5 行...

获取 python 中单个目录下的所有目录和文件的最短方法是什么?

您可以清空 dirs 列表并且 os.walk() 不会递归:

for root, dirs, files in os.walk(home_path):
    for dir in dirs:
        # do something with each directory
    dirs[:] = []  # clear directories.

注意dirs[:] =切片分配;我们正在替换 dirs 中的元素(而不是 dirs 引用的列表),以便 os.walk() 不会处理已删除的目录。

这仅在您将 topdown 关键字参数保留为 True 时有效,来自 documentation of os.walk():

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again.

或者,使用 os.listdir() 并自行将名称过滤到目录和文件中:

dirs = []
files = []
for name in os.listdir(home_path):
    path = os.path.join(home_path, name)
    if os.isdir(path):
        dirs.append(name)
    else:
        files.append(name)