鱼C论坛

 找回密码
 立即注册
查看: 2439|回复: 2

[已解决]第30课课后练习第0题

[复制链接]
发表于 2016-3-7 14:12:13 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 一二二四四 于 2016-3-7 16:15 编辑

第0题:
1.为什么会返回一个:该文件夹下共有类型为【】的文件4个,【】是怎么来的呢?谢谢
程序如下:
import os
def countcount():
    os.getcwd()
    file_type = dict()
    all_files = os.listdir(os.curdir)
    for each_file in all_files:
        if os.path.isdir(each_file):
            file_type.setdefault('文件夹',0)
            file_type['文件夹'] += 1
        if os.path.isfile(each_file):
            temp = os.path.splitext(each_file)[1]
            file_type.setdefault(temp,0)
            file_type[temp] += 1

    for each_type in file_type:
        print('该文件夹下共有类型为【%s】的文件%d个' %(each_type,file_type[each_type]))

countcount()


2.补充:不用setdefault的话可以怎么实现呢?
最佳答案
2016-3-7 14:13:10
没有扩展名的文件
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-3-7 14:13:10 | 显示全部楼层    本楼为最佳答案   
没有扩展名的文件
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-3-7 15:20:45 | 显示全部楼层
冬雪雪冬 发表于 2016-3-7 14:13
没有扩展名的文件

谢谢,我把代码改成了下面这样,加入了是否有拓展名的判断,但是执行出来结果还是没变,请帮忙看一下。
import os
def countcount():
    os.getcwd()
    file_type = dict()
    all_files = os.listdir(os.curdir)
    for each_file in all_files:
        if os.path.isdir(each_file):
            file_type.setdefault('文件夹',0)
            file_type['文件夹'] += 1
        elif os.path.isfile(each_file):
            if os.path.splitext(each_file) != '':
                temp = os.path.splitext(each_file)[1]
                file_type.setdefault(temp,0)
                file_type[temp] += 1
            else:
                file_type.setdefault('无拓展名',0)
                file_type['无拓展名'] += 1

    for each_type in file_type:
        print('该文件夹下共有类型为【%s】的文件%d个' %(each_type,file_type[each_type]))

countcount()
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-20 01:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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