繁体   English   中英

如何遍历目录中的子目录并计算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()

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

它可以工作,但是我知道在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 $1}'|grep d|wc -l); echo     $J; if [ $J -gt 0 ]; then echo "GREATER"; fi done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM