如何遍历目录中的子目录并计算python中子目录中的文件

How to iterate through subdirectories in a directory and count the files in the subdirectories in python

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

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

脚本首先依次查看目录中的子目录,然后切换到"looking at"目录,以计算其中的文件。

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

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

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

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

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