|
5鱼币
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]))
红色部分如何理解,有什么作用
本帖最后由 zm_selina 于 2019-11-22 08:07 编辑
os.path.splitext() 方法用于将完整文件的文件名(例如name.txt)分离成文件名和扩展名组成的元组(例如name.txt分离成元组(name,.txt),[0]在这个元组里是name, [1]就是 .txt))
ext = os.path.splitext(each_file)[1] 这里是把每个文件的扩展名做为字符串赋值给变量ext。
|
最佳答案
查看完整内容
os.path.splitext() 方法用于将完整文件的文件名(例如name.txt)分离成文件名和扩展名组成的元组(例如name.txt分离成元组(name,.txt),[0]在这个元组里是name, [1]就是 .txt))
ext = os.path.splitext(each_file)[1] 这里是把每个文件的扩展名做为字符串赋值给变量ext。
|