第30讲 第0题
import osall_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)
type_dict.setdefault(ext, 0)
type_dict += 1
for each_type in type_dict.keys():
print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict))
可以讲一讲这个题的代码嘛 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)# 如果是文件夹,则看 '文件夹' 键是否存在于字典中,不存在将会添加键并将值设为默认值 0
type_dict['文件夹'] += 1# 如果为文件夹,怎文件夹数量加 1
else:
ext = os.path.splitext(each_file)# 如果不是文件夹,则按文本拆分文件名,获取 下标索引为 1 的元素,即文件后缀名
type_dict.setdefault(ext, 0)# 把文件后缀名作为 键,看 该键 是否存在于字典中,不存在将会添加键并将值设为默认值 0
type_dict += 1# 该后缀对应的值加 1
for each_type in type_dict.keys():
print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict))# 打印 键 及其所对应的值
页:
[1]