python实现统计windows上目录(含子目录)大小

使用python实现递归统计目录(含子目录)大小

#-*- coding:utf-8 -*-
import os
import sys

WINDOWS_EXCLUEDE=['$']

def readable(size):
    if size >= 0  and size < 1024:
        return '%i' % size
    elif size >= 1024 and size < 1024*1024:
        return '%.1fK' % (size/1024.0)
    elif size >= 1024*1024 and size < 1024*1024*1024:
        return '%.1fM' % (size/1024.0/1024.0)
    elif size >= 1024*1024*1024 and size < 1024*1024*1024*1024:
        return '%.1fG' % (size/1024.0/1024.0/1024.0)
    elif size >= 1024*1024*1024*1024:
        return '%.1fT' % (size/1024.0/1024.0/1024.0/1024.0)

def getsize(dir):
    sub_dirs = os.listdir(dir)
    count = 0
    for sub_dir in sub_dirs:
        sub_path = os.path.join(dir, sub_dir)
        if os.path.isfile(sub_path):
            count += os.path.getsize(sub_path)
        else:
            count += getsize(sub_path)
    return count


def du1(path):
    dirs = os.listdir(path)
    dirs.sort()
    count = 0
    for dir in dirs:
        exclude = False
        for ec in WINDOWS_EXCLUEDE:
            if dir.startswith(ec):
                exclude = True
        if not exclude:
            dir_path = os.path.join(path, dir)
            if os.path.isfile(dir_path):
                size = os.path.getsize(dir_path)
                count += size
                print '%s\t%s' % (readable(int(size)), dir_path.decode('GBK').encode('utf-8'))
            elif os.path.isdir(dir_path):
                size = getsize(dir_path)
                count += size
                print '%s\t%s' % (readable(int(size)), dir_path.decode('GBK').encode('utf-8'))

    print 'total: %s' % readable(count)

if __name__ == '__main__':
    if len(sys.argv) == 2:
        curpath = sys.argv[1]
    else:
        curpath = '.'
    du1(curpath)


你可能感兴趣的:(Python)