【问题标题】:How to iterate through subdirectories in a directory and count the files in the subdirectories in python如何遍历目录中的子目录并在python中计算子目录中的文件
【发布时间】:2015-11-26 12:49:51
【问题描述】:

我想遍历目录中的子目录并获取每个子目录中的文件数。我的(凌乱的)解决方案如下所示:

import os, sys
import subprocess

def Count_files_in_subd():

    for root, dirs, files in os.walk("/Path/to/directory", topdown=False):
        for name in dirs:
            print name
            f = os.path.join(root, name)
            os.chdir(f)
            i=0
            for filename in os.listdir(os.getcwd()):
                i+=1
            print i


Count_files_in_subd()

脚本首先依次查看目录中的子目录,然后更改它正在“查看”的目录,以计算其中的文件。

它有效,但我知道在 python 中有更好的方法来做到这一点。我查看了关于 SO 的不同问题,但是当我尝试大多数解决方案时,每个子目录的文件数只有一个,并且我假设该目录被计为文件。任何有关如何更好地做到这一点的帮助将不胜感激。

【问题讨论】:

    标签: python count directory subdirectory


    【解决方案1】:

    您可以重新编码如下以显示每个文件夹中的文件数:

    import os
    
    def Count_files_in_subd():
        for root, dirs, files in os.walk("/Path/to/directory"):
            print "{} in {}".format(len(files), root)
    
    Count_files_in_subd()
    

    root 保存当前正在遍历的文件夹,files 已经保存了该文件夹中的所有文件,因此您只需要计算它们就是 len(files)

    dirs 保存在当前文件夹中找到的所有文件夹(接下来将访问该文件夹)。如果您不想访问某个文件夹,可以将其从此列表中删除。

    这将为您提供以下类型的输出:

    5 in /Path/to/directory
    10 in /Path/to/directory/folder_1
    3 in /Path/to/directory/folder_1/deeper
    

    【讨论】:

    • 谢谢你的解释,我的想法有错误:-)
    • 是的,没错,更好的变量名应该是dirpathdirnamesfilenames。您将根传递给 os.walk 函数。
    【解决方案2】:

    您可以在 bash 中执行此操作,它不是那么干净,但是通过递归列表,您可以确保遍历每个目录。

    ls -lR|while read i ; do J=$(echo $i|awk '{print $1}'|grep d|wc -l); echo     $J; if [ $J -gt 0 ]; then echo "GREATER"; fi done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2021-07-09
      • 2011-03-10
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多