【问题标题】:Non-recursive os.walk()非递归 os.walk()
【发布时间】:2011-05-06 06:41:47
【问题描述】:

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

提前谢谢你。

【问题讨论】:

    标签: python os.walk non-recursive


    【解决方案1】:

    灵活的文件计数功能:

    您可以设置递归搜索以及要查找的类型。默认参数: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
    

    【讨论】:

      【解决方案2】:

      清空目录列表

      for r, dirs, f in os.walk('/tmp/d'):
          del dirs[:]
          print(f)
      

      【讨论】:

        【解决方案3】:

        在文件名后添加break for 循环:

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

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

        【讨论】:

        • 我觉得这应该是公认的答案。非常简单准确。
        【解决方案4】:

        我的参数化解决方案是这样的:

        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 :}

        【讨论】:

        • 只有在有 one 子目录时才有效。对于多个子目录,使用while len(dirs) > 0 而不是if
        • @DirkvanOosterbosch:甚至更简单:只是if not recursive: break 无关:您可以使用del dirs[:] 而不是while dirs: dirs.pop()
        【解决方案5】:

        嗯,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()
        

        【讨论】:

          【解决方案6】:
          next(os.walk(...))
          

          【讨论】:

          • 比我想象的还要简单...谢谢!
          • 下一步做什么?
          • 如果你想让递归可选,你必须有两种形式的循环:(
          猜你喜欢
          • 2016-11-19
          • 2013-06-01
          • 2023-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多