import os, os.path def getDirSize(dirPath): size = 0 for tuple in os.walk(dirPath): dpath, subs, files = tuple for f in files: realPath = os.path.join(dpath, f) size += os.stat(realPath).st_size return size def getDirTuples(): def isDir(path): return os.path.isdir(path) dirs = filter(isDir, os.listdir(os.getcwd()) ) def getDirTuple(dirPath): return ( dirPath, getDirSize(dirPath) ) dirTuples = map(getDirTuple, dirs) def myCmp(x, y): return cmp(y[1], x[1]) dirTuples.sort(myCmp) return dirTuples def printDirTuples(): kilo = 1024 meg = 1024**2 gig = 1024**3 dirTuples = getDirTuples() if not dirTuples: print 'No subdirectories in this directory' return for tuple in dirTuples: name, size = tuple[0], int(tuple[1]) unit = '' if size < kilo: unit = 'bytes' elif size < meg: # less than a megabyte unit = 'KB' size /= kilo elif size < gig: # less than a gigabyte unit = 'MB' size /= meg if len(name) > 27: name = name[:27] + '...' spacing = 40 - len(name) spacing = ' ' * spacing print '%s %s %s %s' % (name, spacing, size, unit) return if __name__ == '__main__': printDirTuples()