奔跑的赵云 发表于 2020-11-28 10:32:05

求助30.0

import os
all_files = os.listdir(os.curdir)
type_dict = dict()

for each_file in all_files:
    if os.path.isdir(each_file):
      type_dict.setdefault('文件夹',0) ##这里是不是每次都会将键的值赋值为0 那为什么会得出结果
      type_dict['文件夹'] += 1
    else:##判断文件名
      ext = os.path.splitext(each_file)
      type_dict.setdefault(ext,0) ##和上面一样的问题,不太明白这个0是什么意思??
      type_dict += 1

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

suchocolate 发表于 2020-11-28 10:45:17

本帖最后由 suchocolate 于 2020-11-28 11:05 编辑

字典 setdefault() 方法: 如果键不存在于字典中,将会添加键并将值设为默认值。
type_dict.setdefault('文件夹',0)
# 如果字典里不存在‘文件夹’这个键,就添加这个键,并赋值0
# 如果字典里存在‘文件夹’这个键,就不添加键,只返回该键的值。如果你脚本方式运行,不print是不显示的。

多次判断是否有键做了很多无用功,直接换成变量更合理,同时利用os.path.isfile函数判断。
import os


def main():
    all_files = os.listdir('.')
    file_counter = 0
    dir_counter = 0
    for each_file in all_files:
      if os.path.isfile(each_file):
            file_counter += 1
      else:
            dir_counter += 1
    print(f'该文件夹下共文件夹{dir_counter}个, 文件{file_counter}个。')


if __name__ == '__main__':
    main()

奔跑的赵云 发表于 2020-11-28 11:03:16

suchocolate 发表于 2020-11-28 10:45
字典 setdefault() 方法: 如果键不已经存在于字典中,将会添加键并将值设为默认值。
type_dict.setdefault ...

感谢大哥感谢大哥{:10_298:}
页: [1]
查看完整版本: 求助30.0