1. 程式人生 > >python獲取檔案及資料夾大小

python獲取檔案及資料夾大小

@1.獲取檔案大小

使用os.path.getsize函式,引數是檔案的路徑。

@2.獲取資料夾大小,即遍歷資料夾,將所有檔案大小加和。遍歷資料夾使用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'