【问题标题】:Return number of files in directory and subdirectory返回目录和子目录中的文件数
【发布时间】:2013-05-30 09:44:51
【问题描述】:

试图创建一个函数,返回找到目录及其子目录的文件数。只是需要帮助开始

【问题讨论】:

    标签: python recursion


    【解决方案1】:

    单线

    import os
    cpt = sum([len(files) for r, d, files in os.walk("G:\CS\PYTHONPROJECTS")])
    

    【讨论】:

    • 您能解释一下为什么需要 sum 函数吗?为什么 len(files) 不够用?
    • @GWarner os.walk 产生了多组文件(来自每个子目录)。您必须对每组的长度求和才能获得文件的数量。如果您使用 len(files),那么您会得到一个列表,其中每个元素是其关联子目录中的文件数。
    • 请注意,您需要使用正斜杠(或 \\)而不是此处的反斜杠,否则 python 认为您正在使用转义符。
    【解决方案2】:

    使用os.walk。它会为你做递归。示例见http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/。

    total = 0
    for root, dirs, files in os.walk(folder):
        total += len(files)
    

    【讨论】:

      【解决方案3】:

      只需添加一个处理目录的elif 语句:

      def fileCount(folder):
          "count the number of files in a directory"
      
          count = 0
      
          for filename in os.listdir(folder):
              path = os.path.join(folder, filename)
      
              if os.path.isfile(path):
                  count += 1
              elif os.path.isfolder(path):
                  count += fileCount(path)
      
          return count
      

      【讨论】:

      • @OmarSolis 这不是递归的吗?
      • @OmarSolis:什么是递归?
      • os.path.isdir 在 Ubuntu 上为我工作,而不是 os.path.isfolder。
      猜你喜欢
      • 1970-01-01
      • 2017-10-08
      • 2015-06-15
      • 2015-06-28
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多