| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
import os 
 
all_files = os.listdir(os.curdir) # 使用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] += 1 
 
for each_type in type_dict.keys(): 
    print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict[each_type])) 
 
 
多谢帮忙注解哈红色字体部分的作用或含义 
 
 
看代码注释: 
 
- # for 循环遍历通过 os.listdir 获取的文件与文件夹
 
 - for each_file in all_files:
 
  
-     # 判断此时 for 循环遍历到的对象是不是文件夹
 
 -     if os.path.isdir(each_file):
 
  
-         # 若是文件夹,则用 setdefault 来设置字典键值对
 
 -         # setdefault 方法,第一个参数为字典的 key,第二个为默认值 default,若 key 不存在于字典中,则设置该字典元素为 key:default 加入字典中
 
 -         type_dict.setdefault('文件夹', 0)
 
  
-         # 统计文件夹个数 +1
 
 -         type_dict['文件夹'] += 1
 
 -   
 
 -     else:
 
 -         # 反之则为文件,此时用 splitext 来切割文件名与后缀,并读取后缀赋值为 ext
 
 -         ext = os.path.splitext(each_file)[1]
 
 -         # 同 if 中的功能,若不存在 ext 键,则设置默认值 0 后加入字典
 
 -         type_dict.setdefault(ext, 0)
 
 -         # 统计对应文件个数
 
 -         type_dict[ext] += 1
 
  
- # 循环打印字典中的键,以及字典对应统计个数
 
 - for each_type in type_dict.keys():
 
 -     print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict[each_type]))
 
  复制代码 
 
 
 |   
 
 
 
 |