Skip to main content
 首页 » 编程设计

python之获取从字节到 gb python 的百分比

2024年11月24日18bonelee

我正在开发一个检查文件夹大小的程序,然后打印出最大使用量的百分比,即 50GB。我遇到的问题是,如果数据只有 1mb 或不是 gb 的小数字,我无法获得准确的百分比。我怎样才能改进我的代码来解决这个问题。

import math, os 
 
def get(fold): 
        total_size = 0 
 
        for dirpath, dirnames, filenames in os.walk(fold): 
            for f in filenames: 
                fp = os.path.join(dirpath, f) 
                size = os.path.getsize(fp) 
                total_size += size 
 
        size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") 
        i = int(math.floor(math.log(total_size, 1024))) 
        p = math.pow(1024, i) 
        s = round(total_size / p, 2) 
 
        return "%s %s" % (s, size_name[i]) 
 
per = 100*float(get(fold))/float(5e+10) 
print(per) 

请您参考如下方法:

您可能低估的一个地方是您在不考虑 block 大小的情况下添加文件大小。例如,在我的系统上,分配 block 大小为 4096 字节。因此,如果我“回显 1 > test.txt”,这个 1 字节的文件占用 4096 字节。我们可以重新编写代码以尝试解决 block 问题:

import math 
import os 
 
SIZE_NAMES = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") 
 
def get(fold): 
    total_size = 0 
 
    for dirpath, _, filenames in os.walk(fold): 
        for f in filenames: 
            fp = os.path.join(dirpath, f) 
            stat = os.stat(fp) 
            size = stat.st_blksize * math.ceil(stat.st_size / float(stat.st_blksize)) 
            total_size += size 
 
    i = int(math.floor(math.log(total_size, 1024))) 
    p = math.pow(1024, i) 
    s = round(total_size / p, 2) 
 
    return "%s %s" % (s, SIZE_NAMES[i]) 

尽管 getsize() 计数不足会影响所有文件,但按百分比计算,它对较小文件的影响更大。当然,目录节点也会占用空间。另外,这个计算有几个问题:

per = 100*float(get(fold))/float(5e+10) 

首先,它失败了,因为 fold() 返回了一个类似 '122.23 MB' 的字符串,而 float() 不喜欢。其次,它没有考虑到数字的单位,在float()代码中已经调整过,但在这里没有调整。最后,它没有解决千兆字节与千兆字节的问题(如果没有别的,在评论中。)即空间在 fold() 代码中减少了 1024 的幂,但在这里除以 1000 的幂。我的返工:

number, unit = get(fold).split()  # "2.34 MB" -> ["2.34", "MB"] 
number = float(number) * 1024 ** SIZE_NAMES.index(unit)  # 2.34 * 1024 ** 2 
print("{0:%}".format(number / 500e9))  # percentage of 500GB