| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
 本帖最后由 火焰纹章觉醒 于 2016-12-25 18:29 编辑  
- import os
 
 - all_file = os.listdir(input('请输入要查询的地址:')) 
 
  
- #如果把‘input('请输入要查询的地址:')’改成 ‘os.curdir’就正确
 
  
- temp = dict()
 
 - for each_file in all_file:
 
 -     if os.path.isdir(each_file):
 
 -         temp.setdefault('文件夹',0)    #好像是这里的问题
 
 -         temp['文件夹'] += 1
 
 -     else:
 
 -         type1 = os.path.splitext(each_file)[1]
 
 -         temp.setdefault(type1,0)
 
 -         temp[type1] += 1
 
 - for name in temp.keys():
 
 -     print('一共有[%s]类型的文件[%d]个。' %(name,temp[name]))
 
 - print(temp)
 
 -         
 
  复制代码 
 
 
======================================================= 
如果‘input('请输入要查询的地址:')’ 这个就不能打印出‘文件夹’这几个字,但是改成‘os.curdir’就可以正常打印。不是很明白原因,而且好像‘ temp.setdefault('文件夹',0)’这句话在我这段代码中就没有意义了,是什么原因呢,请教一下。
做了一个小小的实验: 
>>> import os 
>>> os.path.isdir("308") 
True 
>>> os.path.isdir("e://Python27") 
True 
>>> os.path.isdir("Python27") 
False 
>>> print(os.getcwd()) 
C:\Users\Administrator\Desktop 
>>>  
 
这说明isdir需要完整的路径来判断是否是文件夹,除非该文件夹在当前工作目录,就是os.curdir。 
 
所以lz的代码中的 
    if os.path.isdir(each_file): 
        temp.setdefault('文件夹',0)    #好像是这里的问题 
        temp['文件夹'] += 1 
if一直返回的是false,后面的也就一直没有执行, 
 
 
 |   
- 
 
 
 
 
 
 
 
 |