|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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]))
求大佬解释
if os.path.isdir(each_file):
type_dict.setdefault('文件夹', 0)
type_dict['文件夹'] += 1
这个是干嘛用的
删了好像不影响结果诶
本帖最后由 jackz007 于 2019-5-1 00:59 编辑
如果删除这些语句,字典 type_dict 中就不会出现文件夹数量的统计值,其他的倒不受影响。
- all_files = os.listdir(os.curdir) # all_files = 当前目录内所有的文件夹和文件
- type_dict = dict() # 初始化字典 type_dict 为空
- for each_file in all_files: # 枚举当前目录内的每一个文件夹和文件
- if os.path.isdir(each_file): # 如果 each_file 是一个子目录
- type_dict.setdefault('文件夹', 0) # 如果字典 type_dict 中不存在键'文件夹',就新建此键,并设置初始键值为 0
- type_dict['文件夹'] += 1 # 字典 type_dict 键 '文件夹' 的键值加 1,也就是文件夹的计数值加 1
- else: # 否则 each_file 应该是一个普通文件
- ext = os.path.splitext(each_file)[1] # 分离出文件扩展名,保存到变量 ext 中
- type_dict.setdefault(ext, 0) # 如果字典 type_dict 中不存在当前文件扩展名的键,就新建此键,并设置初始键值为 0
- type_dict[ext] += 1 # 字典 type_dict 中,以当前文件扩展名为键的值加 1,也就是此文件类型的计数值加 1
- for each_type in type_dict.keys(): # 枚举字典 type_dict 中所有的键和值
- print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict[each_type]))
复制代码
|
|