用python计算文件夹大小

   今天c盘空间不足了,就想看看那个文件夹在浪费空间,可是右键属性一个一个太累了,就想试着写个脚本,如下:

import os
import glob
import sys

def getdirsize(dirname):
'''give the directory name, return the size of it.'''
  size = 0
  for (curdir, subdirs, files) in os.walk(dirname):
    for file in files:
      file = os.path.join(curdir, file)
      try:
        size += os.stat(file).st_size
      except:
        pass
  return int(size/1024/1024)

def listdirsize(dirname):
'''give the directory name, return the list of each subdirectory in the form of (name, size). '''
  dirlist = [ item for item in glob.glob(dirname + '\*') if os.path.isdir(item)]
  result = [ (subdir, getdirsize(subdir)) for subdir in dirlist]
  return result

虽然是个小程序,而且写得也并不怎么好,不过算是首次解决现实中的小问题,呵呵,继续发掘python的力量吧...

原文地址:https://www.cnblogs.com/xiaobaibuhei/p/2772472.html