Python脚本小工具: 按文件夹大小排序

Windows资源管理器按大小排序只能排文件,不能排文件夹。当磁盘空间不足时,往往需要找到哪个文件夹占用最多。可以通过Python脚本实现,对当前目录下的文件和文件夹大小一起排序。

先看效果:脚本在DOS中运行的示例
再上代码:

# Script to list the files and folders in the current path, sorted by size 

import sys, os, time

g_dot = 0  # quantity of '.' printed
g_time = time.time()

def getFolderSize(folder):
    global g_dot
    global g_time
    size = 0
    for root, dirs, files in os.walk(folder):
        now = time.time()
        if now - g_time > 0.2:
            print('.', end='', flush=True)
            g_dot += 1
            g_time = now
        
        try:
            size = size + sum([os.path.getsize(os.path.join(root, f)) for f in files])
        except:
            continue
        
    return size

def byte(n):  # output KB/MB/GB.. from number of Bytes
    d = len(str(n))
    if d == 0:
        return ('', '')
    elif d <= 3:
        return (n / 1, 'Byte')
    elif d <= 6:
        return (n / 10**3, 'KB')
    elif d <= 9:
        return (n / 10**6, 'MB')
    else:
        return (n / 10**9, 'GB')

def main():
    if len(sys.argv) == 1:
        path = '.'
    else:
        path = sys.argv[1]
        if not os.path.exists(path):
            print('"%s" does not exist.' % path)
            return -1
        elif not os.path.isdir(path):
            print('"%s" is not a folder.' % path)
            return -1
    
    global g_dot
    print('.', end='', flush=True)
    g_dot +=1
    
    lstFiles = []
    for f in os.scandir(path):
        prefix = ''
        if f.is_file():
            n = f.stat().st_size
            #n = os.path.getsize(f)
        else:
            prefix = '<DIR> '
            n = getFolderSize(f.path)
        lstFiles.append((prefix + f.name, n))

    if len(lstFiles) == 0:
        print('\b \b'*g_dot, end='', flush=True)
        print('Nothing in this directory!')
        return 0

    lstSorted = sorted(lstFiles, key = lambda item: item[1], reverse = True)
    width = len('{:,d}'.format(lstSorted[0][1]))
    total = 0
    lines = []
    for x in lstSorted:
        total = total + x[1]
        size = '{:,d}'.format(x[1]).rjust(width, ' ')
        line = size + ' Byte\t' + x[0]
        lines.append(line)
    
    print('\b \b'*g_dot, end='', flush=True)
    print("Total %.2f %s" % byte(total))
    print('\n'.join(lines))
    
    return 0


if __name__ == '__main__':
    main()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值