您的位置:首页 > 编程语言 > Python开发

用python对指定目录下的所有文件(夹)大小进行排序

2016-07-29 18:56 639 查看
Windows的某个目录下sort by size只能对该目录下的文件进行排序,不能对目录下的文件夹进行排序,而手工点击右键逐个计算文件夹的大小效比较低。在此我用用python对指定目录下的所有文件(夹)大小进行排序,代码如下:

#! /usr/bin/env python

'''

Sort the size of floders and files with given directory.

Author: Sean.Xu

'''

import os

import os.path

import datetime

L={}

k={}

rootdir = 'C:\\Windows'

def getdirsize(dir):

    size = 0

    for parent, dirnames, filenames in os.walk(dir):

        for filename in filenames:

            try:

                name = os.path.join(parent, filename)

                size += os.path.getsize(name)

            except:

                continue

    return size

def getsizename(size):

    if (size > 1024*1024*1024.0):

        numstr = str(size/(1024*1024*1024.0))

        sizename = numstr[:(numstr.index('.')+3)]+'GB'

    elif (size > 1024*1024.0):

        numstr = str(size/(1024*1024.0))

        sizename = numstr[:(numstr.index('.')+3)]+'MB'

    elif (size > 1024.0):

        numstr = str(size/1024.0)

        sizename = numstr[:(numstr.index('.')+3)]+'KB'

    else:

        sizename = str(size) +'Bytes'

    return sizename

# proc start

starttime = datetime.datetime.now()

filenames = os.listdir(rootdir)

for filename in filenames:

    fullpath = os.path.join(rootdir, filename)

    if os.path.isdir(fullpath):

        L[filename] = getdirsize(fullpath)

    else:

        L[filename] = os.path.getsize(fullpath)

k = sorted(L.items(), key=lambda L:L[1], reverse = True)

endtime = datetime.datetime.now()

print 'The directory of %s has %d items(folder and file).' %(rootdir, len(k))

print 'It took %ds to sort the size of these items. The result is as below:' %(endtime - starttime).seconds

for i in range(len(k)):

    print k[i][0],"\t",getsizename(k[i][1])

示例中是对C的Windows目录下的文件(夹)进行排序,部分结果如下:

D:\python_example>sortfilesize.py

The directory of C:\Windows has 131 items(folder and file).

It took 68s to sort the size of these items. The result is as below:

Installer       14.30GB

WinSxS  3.92GB

System32        2.35GB

assembly        849.10MB

Microsoft.NET   387.80MB

Fonts   376.48MB

Panther         180.95MB

Symbols         167.64MB

IME     165.17MB

SoftwareDistribution    150.48MB

SystemApps      116.69MB

Speech  110.44MB

INF     73.98MB

Speech_OneCore  50.81MB

servicing       48.02MB

InputMethod     34.57MB

Boot    30.72MB

Performance     28.19MB

Media   26.35MB

......

花了68秒对该目录下的131个文件(夹)进行了排序,并且显示了大小,结果一目了然。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息