统计一个目录下各类文件数量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chekongfu/article/details/82716359

最近笔者在研究tomcat底层架构,肯定要扒一扒tomcat源码,笔者希望知道工作量有多大,也就是统计一下tomcat源码中文件有多少。笔者首先是个比较懒得人(不懒也不会干IT),所以不可能手动的去统计,也不会自己写代码去统计,然后在网上找了一个java版本的代码。

java代码如下:

package statistic;

import java.io.File;

public class Test {
	static int count=0;
	public static void main(String[] args) {
        getFile("D:/eclipse/work/apache-tomcat-6.0.35-src");
        System.out.println("共有"+count+"个文件");
    }
 
    public static void getFile(String filepath) {
        //com.bizwink.cms.util.Convert con = new com.bizwink.cms.util.Convert();
        File file = new File(filepath);
        File[] listfile = file.listFiles();
        for (int i = 0; i < listfile.length; i++) {
            //System.out.println("****** = "+listfile[i].getPath().toString());
            if (!listfile[i].isDirectory()) {
                //com.bizwink.cms.util.Convert con = new com.bizwink.cms.util.Convert();
                String temp=listfile[i].toString().substring(7,listfile[i].toString().length()) ;
                //System.out.println("temp=="+temp);
                //con.convertFile(listfile[i].toString(), "D:\\newtest"+temp, 0, 3);
                count++;
                //System.out.println("文件"+count+"---path=" + listfile[i]);
            } else {
                getFile(listfile[i].toString());
            }
        }
    }
}

运行结果如下:
这里写图片描述

总体来讲,此代码中规中矩,统计倒是很准确,但是tomcat源码中有各类的文件,笔者希望统计信息更详细一点,加上笔者最近在学习python,在加上突然想到该案例是一个非常好的递归案例,然后笔者一时技痒,自己写了几行代码:

python代码如下:

#_*_ coding:utf-8 _*_

'''
Created on 2018年9月15日

@author: admin
'''

import os.path

rootFolder = 'D:/eclipse/work/apache-tomcat-6.0.35-src'

#后缀名字典表
result = {'folder':0}

def statistic(folder):
    for temp in os.listdir(folder):
        filepath = os.path.join(folder,temp)
        
        #判断是否文件夹,如果是文件夹,则继续递归遍历
        if (os.path.isdir( filepath )):
            result['folder'] += 1
            statistic(filepath)
        else:
            (name, extension)= os.path.splitext(temp)
            #判断后缀名是否在后缀名字典表中
            #如果有,直接将该后缀名文件数加1
            if result.has_key(extension):
                result[extension] += 1
            #如果没有,则添加新的字典项目,该后缀名文件数置位1
            else:
                result[extension] = 1
                
if __name__ == '__main__':
    statistic( rootFolder )
    sum = 0
    for name in result.keys():
        if( name == '' ):
            print('该文件夹下共有类型为【无后缀名】的文件%s个'%(result[name]))
        else:
            print('该文件夹下共有类型为【%s】的文件%s个'%(name, result[name]))
        sum += result[name]
    print("共有目录及文件%s个"%sum)

运行结果如下:
这里写图片描述

注意:上面代码第21行代码是一个坑,因为开始笔者写的是os.path.isdir( temp ),会一直报错,因为isdir()函数里面传入的参数是一个绝对路径,不然一直会返回false。

猜你喜欢

转载自blog.csdn.net/chekongfu/article/details/82716359