鱼C论坛

 找回密码
 立即注册
查看: 3020|回复: 3

30讲,字典类型打印结果报错

[复制链接]
发表于 2016-4-26 17:33:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. # ——*——   coding:cp936   -*-

  2. #编写一个程序,统计当前目录下每个文件类型的文件数

  3. import os

  4. all_files = os.listdir(os.curdir) #os.curdir表示当前目录
  5. type_dict = dict()   #定义type_dict为字典


  6. #def file_type(all_files,type_dict,)


  7. for each_file in all_files:
  8.     if os.path.isdir(each_file):   #isdir(each_file)表示判断制定路径是否存在且是一个目录
  9.         type_dict.setdefault('文件夹', 0) #设置默认值
  10.         type_dict['文件夹'] += 1  #列表中内容项追加


  11.     else:
  12.         ext = os.path.splitext(each_file)[1]  #splitext(path)分离文件名与扩展名,返回(f_name,f_extension)元组
  13.         type_dict.setdefault(ext,0)
  14.         type_dict[ext] += 1



  15. for each_type in type_dict.keys():   #返回字典所有的键
  16.     #num = type_dict(each_type)
  17.     #print('该文件夹下共有类型为【%s】的文件 %d个' % each_type, type_dict[each_type])
  18.     print each_type
  19.     print type_dict(each_type)
复制代码

  1. >>>
  2. .py

  3. Traceback (most recent call last):
  4.   File "I:\python exercise\30lesson\0.py", line 31, in <module>
  5.     print type_dict(each_type)
  6. TypeError: 'dict' object is not callable
复制代码


最后一句打印语句,不知道怎么搞啦
有可能还是跟python 2 有关
哪位帮忙解决下
python2和3的问题,是个头疼的问题啊
多谢啦
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-4-26 20:47:16 | 显示全部楼层
没太仔细看你的代码,但是type_dict(each_type),明显是不对的,你是不是想要type_dict[each_type]
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-4-27 10:00:41 | 显示全部楼层
挥舞乾坤 发表于 2016-4-26 20:47
没太仔细看你的代码,但是type_dict(each_type),明显是不对的,你是不是想要type_dict[each_type]

恩 是啊  type_dict[each_type] 这个是对的   写错啦
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-4-27 11:18:07 | 显示全部楼层
python 2 中print 语句这么写 就对啦
  1.     print "该文件夹下共有类型为【%s】的文件 %d个" % (each_type, type_dict[each_type])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-20 20:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表