45

我正在寻找一种方法来进行非递归os.walk()步行,就像os.listdir()作品一样。但我需要以同样的方式os.walk()返回。任何的想法?

先感谢您。

4

6 回答 6

50

在文件名之后添加一个breakfor 循环:

for root, dirs, filenames in os.walk(workdir):
    for fileName in filenames:
        print (fileName)
    break   #prevent descending into subfolders

这是因为(默认情况下)os.walk首先列出请求文件夹中的文件,然后进入子文件夹。

于 2016-10-31T19:46:30.087 回答
42
next(os.walk(...))
于 2010-11-07T12:00:44.837 回答
6

我更参数化的解决方案是:

for root, dirs, files in os.walk(path):  
    if not recursive:  
        while len(dirs) > 0:  
            dirs.pop()  

    //some fency code here using generated list

编辑:修复,if/while 问题。谢谢,@Dirk van Oosterbosch :}

于 2013-01-30T15:51:28.913 回答
1

好吧,Kamiccolo 的意思更符合这个:

for str_dirname, lst_subdirs, lst_files in os.walk(str_path):
    if not bol_recursive:
          while len(lst_subdirs) > 0:
              lst_subdirs.pop()
于 2013-11-15T17:07:08.540 回答
0

清空目录列表

for r, dirs, f in os.walk('/tmp/d'):
    del dirs[:]
    print(f)
于 2021-04-07T12:32:58.400 回答
0

灵活的文件计数功能:

您可以设置递归搜索以及要查找的类型。默认参数:file_types=("", )查找任何文件。该参数file_types=(".csv",".txt")将搜索 csv 和 txt 文件。

from os import walk as os_walk

def count_files(path, recurse=True, file_types = ("",)):
    file_count = 0
    iterator = os_walk(path) if recurse else ((next(os_walk(path))), )
    for _, _, file_names in iterator:
        for file_name in file_names:
            file_count += 1 if file_name.endswith(file_types) else 0
    return file_count
于 2021-12-03T16:25:56.543 回答