使用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.csdn.net/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'