2011-10-10 76 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) –