|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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)
- 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]))
复制代码
这道题为什么不用列表而是用字典呢?
这两行代码是什么意思呢?
type_dict['文件夹'] += 1
type_dict[ext] += 1
谢谢!!!
这道题为什么不用列表而是用字典呢?----需要用key保持文件类型,用value保存数量
type_dict['文件夹'] += 1 ----如果是文件夹,则文件夹数量加一
type_dict[ext] += 1 ----如果是某个扩展名的文件,则此扩展名文件数量加一。
|
|