程序1
编写一个程序,统计当前目录下每个文件类型的文件数,程序实现如图:
1 import os 2 3 4 def countfile(path): 5 dict1 = {} # 定义一个字典 6 all_files = os.listdir(path) 7 for each_file in all_files: 8 if os.path.isdir(os.path.join(path,each_file)): 9 dict1.setdefault('文件夹', 0) 10 # setdefault:如果字典中包含有给定键, 11 # 则返回该键对应的值,否则返回为该键设置的值。 12 dict1['文件夹'] += 1 # 参考以前分享的字典修改 13 else: 14 ext = os.path.splitext(each_file)[1] 15 # 分离文件名与扩展名,返回(f_name, f_extension)元组 16 dict1.setdefault(ext, 0) 17 dict1[ext] += 1 18 #print(dict1) 19 for each_type in dict1.keys(): 20 print('该文件夹下共有【%s】类型的文件%d个' 21 % (each_type, dict1[each_type])) 22 23 24 path = input('输入要统计的目录: ') 25 countfile(path)