Skip to main content
 首页 » 编程设计

python之os.walk once python 的干净方法

2025年05月04日36kenshinobiy

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

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)