使用os.path.getsize函数,参数是文件的路径。
获取文件夹大小,即遍历文件夹,将所有文件大小加和。遍历文件夹使用os.walk函数
import os
from os.path import join, getsize
def getdirsize(dir):
size = 0L
for root, dirs, files in os.walk(dir):
size += sum([getsize(join(root, name)) for name in files])
return size
if '__name__' == '__main__':
filesize = getdirsize(r'c:\windows')
print 'There are %.3f' % (size/1024/1024), 'Mbytes in c:\\windows'
源自:http://blog.youkuaiyun.com/cashey1991/article/details/
分隔符
刚才遇到了这个问题,比如我只想要一个文件夹中所有的’.tmp’后缀的文件,那么代码改成:
import os
from os.path import join, getsize
def getdirsize(dir):
size = 0L
for root, dirs, files in os.walk(dir):
size += sum([getsize(join(root, name)) for name in files if os.path.splitext(name)[1] =='.tmp'])
return size
if '__name__' == '__main__':
filesize = getdirsize(r'c:\windows')
print 'There are %.3f' % (size/1024/1024), 'Mbytes in c:\\windows'