Python-读取文件的大小

1.python读取文件以及文件夹的大小

 

1. os.path.getsize(file_path):file_path为文件路径

import os
os.path.getsize('d:/svn/bin/SciLexer.dll')
#1479904

2. 遍历文件夹,将所有文件大小加和, os.walk()遍历文件夹

import os
from os.path import join, getsize


def getdirsize(dir):
    size = 0
    for root, dirs, files in os.walk(dir):
        size += sum([getsize(join(root, name)) for name in files])
    return size

 

 

2.将文件大小进行格式化

def size_format(size):
    if size < 1000:
        return '%i' % size + 'size'
    elif 1000 <= size < 1000000:
        return '%.1f' % float(size/1000) + 'KB'
    elif 1000000 <= size < 1000000000:
        return '%.1f' % float(size/1000000) + 'MB'
    elif 1000000000 <= size < 1000000000000:
        return '%.1f' % float(size/1000000000) + 'GB'
    elif 1000000000000 <= size:
        return '%.1f' % float(size/1000000000000) + 'TB'

 

posted @ 2019-07-29 14:02  YF-海纳百川  阅读(27400)  评论(0编辑  收藏  举报