关于os的一系列问题:统计当前目录下每个文件类型的文件数

来源:互联网 发布:假短信软件 编辑:程序博客网 时间:2024/06/05 05:58

需求:
统计当前目录下不同类型的文件的个数
E:\Python Program
该文件夹下共有【.txt】的文件11个
该文件夹下共有【.mp3】的文件1个
该文件夹下共有【.py】的文件19个
该文件夹下共有【文件夹】的文件4个
该文件夹下共有【.bak】的文件1个
该文件夹下共有【.pkl】的文件1个

# -*- coding: utf-8 -*-import osprint (os.getcwd())all_files=os.listdir(os.curdir)type_dict=dict()for each_file in all_files:    if os.path.isdir(each_file):        type_dict.setdefault("文件夹",0)        type_dict["文件夹"]+=1    else:        ext=os.path.splitext(each_file)[1]        type_dict.setdefault(ext,0)        type_dict[ext]+=1for each_type in type_dict.keys():    print ("该文件夹下共有【%s】的文件%d个" %(each_type,type_dict[each_type]))

注:os.path.splitext(path) #分割路径,返回路径名和文件扩展名的元组
参考:
http://bbs.fishc.com/forum.php?mod=viewthread&tid=45649&extra=page%3D1%26filter%3Dtypeid%26typeid%3D398

0 0