1

新手问题来了!

我正在尝试按目录中的文件扩展名获取文件大小的总和。到目前为止,我正在使用它的修改版本(通过Python - Acquiring a count of file extensions across all directory)来计算它们。

尝试使用 os.path.getsize() 然后使用 sum() 将它们相加,但我得到零或错误。

我错过了什么?

我复制的代码是这样的:

import os
import collections
extensions = collections.defaultdict(int)

place = input('Type the directory path: ')

for path, dirs, files in os.walk(place):
   for filename in files:
       extensions[os.path.splitext(filename)[1].lower()] += 1

for key,value in extensions.items():
    print ('Extension: ', key, ' ', value, ' items')
4

2 回答 2

2

你试过这个吗?

import os
import collections
extensions = collections.defaultdict(int)
size = collections.defaultdict(int)

for path, dirs, files in os.walk('/'):
   for filename in files:
       extensions[os.path.splitext(filename)[1].lower()] += 1
       size[os.path.splitext(filename)[1].lower()] += os.path.getsize(path+os.sep+filename)

for key,value in extensions.items():
    print 'Extension: ', key, ' ', value, ' items'

for key,value in size.items():
    print 'Extension: ', key, ' ', value, ' size'

这是基于您的链接

于 2013-10-29T09:40:40.240 回答
1

只是替换了参考代码中的一行:

import os
import collections
extensions = collections.defaultdict(int)

for path, dirs, files in os.walk('.'):
   for filename in files:
       # add file size to the extension dictionary item, instead of add 1 
       extensions[os.path.splitext(filename)[1].lower()] += os.path.getsize(os.path.join(path,filename))

for key,value in extensions.items():
    print 'Extension: %s, Size: %s' % (key, value)
于 2013-10-29T09:39:33.707 回答