2011-10-10 74 views
0

我想根据它们的扩展名对命令目录中的文件进行计数。 所以,我创建了一个包含cwd中所有文件的列表,然后是一个只包含扩展名的列表,然后我从该列表中创建了一个字典。我使用count参数创建了字典,但我不知道如何处理这个。我的字典看起来像“{'txt':0,'doc':0}”。python - 计数文件(无法计算字典中的值)

import os,glob 

def myfunc(self): 
    mypath=os.getcwd() 
    filelist=glob.glob("*") #list with all the files in cwd 
    extension_list=[os.path.splitext(x)[1][1:] for x in filelist] #make list with the extensions only 
    print(extension_list) 

    count=0; 
    mydict=dict((x,count) for x in extension_list) #make dict with the extensions as keys and count as value 
    print(mydict) 

    for i in mydict.values(): #i must do sth else here.. 
     count+=1 
    print(count) 
    print(mydict) 

回答

0

通过扩展列表中,只是想迭代和递增的字典值:

for ext in extension_list: 
    mydict[ext] += 1 
+0

感谢这么简单! – George

2

当然,你只是想在你的循环count += i

虽然有一个很好的数据结构,可以为你做这一切:collections.Counter

1

这是collections.Counter类完美的使用:

>>> from collections import Counter 
>>> c = Counter(['foo', 'foo', 'bar', 'foo', 'bar', 'baz']) 
>>> c 
2: Counter({'foo': 3, 'bar': 2, 'baz': 1}) 
>>> 
+0

哇,认真吗?主要尊重Python收集随机酷的东西。 (1) –