Blueherb In solitude, where we are least alone

计算目录大小

import os,os.path

directory = input('请输入目录或者文件地址:')


def getSzie(path):
    global size
    size = 0
    if os.path.isfile(path):
        size1 = os.path.getsize(path)
        size += size1

    if os.path.isdir(path):
        for file in os.listdir(path):
            #全路径
            filename = os.path.join(path, file)
            if os.path.isfile(filename):
                size2 = os.path.getsize(filename)
                size += size2
            elif os.path.isdir(filename):
                #递归方法调用
                #最后的大小一定要记得加上之前文件的大小
                size += getSzie(filename)

    return size


size = getSzie(directory)
if size <= 1024:
    print('目录大小为:{}字节'.format(size))
elif size > 1024 and size<1024*1024:
    print('目录大小为:{:.2f}KB'.format(size/1024))
else:
    print('目录大小为:{:.2f}MB'.format(size/(1024*1024)))
posted @ 2020-06-20 14:53  无敌-蹦蹦  阅读(133)  评论(0编辑  收藏  举报