鱼C论坛

 找回密码
 立即注册
查看: 1846|回复: 1

python030课课后题

[复制链接]
发表于 2016-12-7 11:44:59 | 显示全部楼层 |阅读模式
1鱼币
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]))





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这组代码中的这段不是很懂,请大神帮忙逐步解答下
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-12-7 11:45:00 | 显示全部楼层
  1. for each_file in all_files:             #遍历当前目录下的所有文件
  2.     if os.path.isdir(each_file):            #如果是个目录的话
  3.         type_dict.setdefault('文件夹', 0)   #默认文件夹的个数为0
  4.         type_dict['文件夹'] += 1            #文件夹的个数加1
  5.     else:
  6.         ext = os.path.splitext(each_file)[1] #如果each_file是文件的话,把文件的扩展名赋值给ext
  7.         type_dict.setdefault(ext, 0)         #给后缀名一个默认值为0 (如果已有值,0不起作用)
  8.         type_dict[ext] += 1                  #这个扩展名的数量加一
  9.         
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-10-16 03:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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