小蜂队 发表于 2022-3-17 08:45:18

论.技术.Python.(旧)零学Python第030讲:使用字典统计文件类型

0. 编写一个程序,统计当前目录下每个文件类型的文件数。



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)   #setdefault() 会在字典中寻找,若是没有 each_file 则会在字典中自动创建
      type_dict['文件夹'] += 1    #该类型 +1
    else:
      ext = os.path.splitext(each_file)
      type_dict.setdefault(ext, 0)
      type_dict += 1

for each_type in type_dict.keys():
    print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict))

学会了 发表于 2022-3-17 14:02:30

:):time::o
页: [1]
查看完整版本: 论.技术.Python.(旧)零学Python第030讲:使用字典统计文件类型