|
发表于 2019-9-12 16:32:28
|
显示全部楼层
if os.path.isdir(each_file):#如果在本地文件夹下面用这个方法是没错的,如果是遍历其他文件夹,需要把地址补全。参考代码:
- import os
- path = 'D:\\txt下载' #把路径赋值给一个变量
- all_files = os.listdir(path)
- type_dict = dict()
- for each_file in all_files:
- if os.path.isdir(os.path.join(path,each_file)): # 用join把需要遍历的文件夹组合成一个完成的路径
- 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]))
复制代码 |
|