编写一个程序,统计当前文件夹下每个文件类型的文件数

来源:互联网 发布:miss外设淘宝店网址 编辑:程序博客网 时间:2024/06/05 03:40
# -*- coding: utf-8 -*-import os.pathimport oslist = os.listdir()print(os.getcwd())txtnumber =0pngnumber =0pynumber= 0docxnumber= 0filenumber =0dict= {'.txt':txtnumber,'.png':pngnumber,'.py':pynumber,'.docx':docxnumber,'文件夹':filenumber}for file in list:    (name,extension)= os.path.splitext(file)    if extension =='.txt':        txtnumber+= 1    if extension =='.png':        pngnumber+= 1    if extension =='.py':        pynumber+= 1    if extension =='.docx':        docxnumber+= 1    if extension =='.txt':        txtnumber+= 1    if extension =='':       dict['文件夹']+= 1for name in dict.keys():    print('该文件夹下共有类型为【%s】的文件%s个'%(name,dict[name]))


#文件夹类型正常打印,其余全部为0

#此处字典初始化时,只是拷贝txtnumber的值,由于没有指针类型,字典的value并不能为一个来自字典外的变量,所以该程序其实并没有改变字典的值

正确代码

# -*- coding: utf-8 -*-import os.pathimport oslist = os.listdir()print(os.getcwd())dict= {'.txt':0,'.png':0,'.py':0,'.docx':0,'文件夹':0}for file in list:    (name,extension)= os.path.splitext(file)    if extension =='.txt':        dict['.txt']+= 1    if extension =='.png':        dict['.png']+= 1    if extension =='.py':       dict['.py']+= 1    if extension =='.docx':       dict['.docx']+= 1    if extension =='':       dict['文件夹']+= 1for name in dict.keys():    print('该文件夹下共有类型为【%s】的文件%s个'%(name,dict[name]))
标准答案:
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)[1]        type_dict.setdefault(ext, 0)        type_dict[ext] += 1for each_type in type_dict.keys():    print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict[each_type]))
1.应动态创建key
2.注意setadefault函数的用法



阅读全文
0 0
原创粉丝点击