Python专题, 语言

使用Python统计各个子文件夹中的文件数量

实现的功能如标题所示,Python代码如下:

"""
This code is supported by the website: https://www.guanjihuan.com
The newest version of this code is on the web page: https://www.guanjihuan.com/archives/26536
"""


def main():
    # 如果子文件夹中所有文件的数量小于5,输出路径。
    count_file_in_sub_directory(directory='./', smaller_than_num=5) 

    # import guan
    # guan.count_file_in_sub_directory(directory='./', smaller_than_num=5)


def count_file_in_sub_directory(directory='./', smaller_than_num=None):
    import os
    from collections import Counter
    dirs_list = []
    for root, dirs, files in os.walk(directory):
        if dirs != []:
            for i0 in range(len(dirs)):
                dirs_list.append(root+'/'+dirs[i0])
    for sub_dir in dirs_list:
        file_list = []
        for root, dirs, files in os.walk(sub_dir):
            for i0 in range(len(files)):
                file_list.append(files[i0])
        count_file = len(file_list)
        if smaller_than_num == None:
            print(sub_dir)
            print(count_file)
            print()
        else:
            if count_file<smaller_than_num:
                print(sub_dir)
                print(count_file)
                print()


if __name__ == '__main__':
    main()
305 次浏览

【说明:本站主要是个人的一些笔记和代码分享,内容可能会不定期修改。为了使全网显示的始终是最新版本,这里的文章未经同意请勿转载。引用请注明出处:https://www.guanjihuan.com

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code