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()
180 次浏览

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

评论说明:
(1)在保留浏览器缓存的前提下,目前支持72小时自主修改或删除个人评论。如果自己无法修改或删除评论,可再次评论或联系我。如有发现广告留言,请勿点击链接,博主会不定期删除。
(2)评论支持Latex公式。把latexpage作为标签放在任何位置,评论中的公式可正常编译,示例:
[latexpage] $Latex formula$ 
(3)本站评论支持代码格式。在代码前后加上以下标签,留言可保留缩进显示代码:
<!-- wp:code --><pre class="wp-block-code"><code>
	代码内容
</code></pre><!-- /wp:code -->

发表回复

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