【轉載】python獲取文件及文件夾大小

使用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'
發佈了27 篇原創文章 · 獲贊 23 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章