在Python中转换文件大小的更好方法

时间:2011-03-04 13:04:31

标签: python filesize

我正在使用一个读取文件的库,并以字节为单位返回其大小。

然后将此文件大小显示给最终用户;为了让他们更容易理解,我明确将文件大小转换为MB除以1024.0 * 1024.0。当然这有效,但我想知道在Python中有更好的方法吗?

更好的是,我的意思是stdlib函数可以根据我想要的类型操作大小。就像我指定MB一样,它会自动将其除以1024.0 * 1024.0。有些人在这些方面做过准备。

16 个答案:

答案 0 :(得分:86)

以下是我使用的内容:

import math

def convert_size(size_bytes):
   if size_bytes == 0:
       return "0B"
   size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
   i = int(math.floor(math.log(size_bytes, 1024)))
   p = math.pow(1024, i)
   s = round(size_bytes / p, 2)
   return "%s %s" % (s, size_name[i])

注意:大小应以字节发送。

答案 1 :(得分:60)

hurry.filesize将以字节为单位大小,并在其中创建一个很好的字符串。

>>> from hurry.filesize import size
>>> size(11000)
'10K'
>>> size(198283722)
'189M'

或者如果你想要1K == 1000(这是大多数用户所假设的):

>>> from hurry.filesize import size, si
>>> size(11000, system=si)
'11K'
>>> size(198283722, system=si)
'198M'

它也有IEC支持(但没有记录):

>>> from hurry.filesize import size, iec
>>> size(11000, system=iec)
'10Ki'
>>> size(198283722, system=iec)
'189Mi'

因为它是由Awesome Martijn Faassen编写的,所以代码很小,清晰且可扩展。编写自己的系统很容易。

这是一个:

mysystem = [
    (1024 ** 5, ' Megamanys'),
    (1024 ** 4, ' Lotses'),
    (1024 ** 3, ' Tons'), 
    (1024 ** 2, ' Heaps'), 
    (1024 ** 1, ' Bunches'),
    (1024 ** 0, ' Thingies'),
    ]

像这样使用:

>>> from hurry.filesize import size
>>> size(11000, system=mysystem)
'10 Bunches'
>>> size(198283722, system=mysystem)
'189 Heaps'

答案 2 :(得分:19)

您可以使用1024 * 1024 bitwise shifting operator代替<<的大小除数,即1<<20获取兆字节,1<<30获取千兆字节等。

我定义了一个常量MBFACTOR = float(1<<20),然后可以与字节一起使用,即:megas = size_in_bytes/MBFACTOR

答案 3 :(得分:14)

这是计算尺寸的紧凑函数

def GetHumanReadable(size,precision=2):
    suffixes=['B','KB','MB','GB','TB']
    suffixIndex = 0
    while size > 1024 and suffixIndex < 4:
        suffixIndex += 1 #increment the index of the suffix
        size = size/1024.0 #apply the division
    return "%.*f%s"%(precision,size,suffixes[suffixIndex])

有关更详细的输出,反之亦然,请参阅:http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/

答案 4 :(得分:7)

以防任何人正在寻找这个问题的反面(我确实这样做),这对我有用:

def get_bytes(size, suffix):
    size = int(float(size))
    suffix = suffix.lower()

    if suffix == 'kb' or suffix == 'kib':
        return size << 10
    elif suffix == 'mb' or suffix == 'mib':
        return size << 20
    elif suffix == 'gb' or suffix == 'gib':
        return size << 30

    return False

答案 5 :(得分:6)

如果您已经知道所需的内容,请参见下文,以一种快速且相对易于阅读的方式在一行代码中打印文件大小。这些单行代码将上面 @ccpizza 的出色答案与我在此处How to print number with commas as thousands separators?阅读的一些方便的格式化技巧结合在一起。

字节

print ('{:,.0f}'.format(os.path.getsize(filepath))+" B")

千位数

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<7))+" kb")

千字节

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<10))+" KB")

兆位

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<17))+" mb")

兆字节

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<20))+" MB")

千兆位

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<27))+" gb")

千兆字节

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<30))+" GB")

兆字节

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<40))+" TB")

显然,他们假设您一开始就大致知道要处理的大小,就我而言(西南伦敦电视台的视频编辑器),大小为MB,有时为GB,用于视频剪辑。


使用PATHLIB更新 为了回应Hildy的评论,以下是我的建议:仅使用Python标准库提供一对紧凑的函数(保持事物“原子”而不是合并它们):

from pathlib import Path    

def get_size(path = Path('.')):
    """ Gets file size, or total directory size """
    if path.is_file():
        size = path.stat().st_size
    elif path.is_dir():
        size = sum(file.stat().st_size for file in path.glob('*.*'))
    return size

def format_size(path, unit="MB"):
    """ Converts integers to common size units used in computing """
    bit_shift = {"B": 0,
            "kb": 7,
            "KB": 10,
            "mb": 17,
            "MB": 20,
            "gb": 27,
            "GB": 30,
            "TB": 40,}
    return "{:,.0f}".format(get_size(path) / float(1 << bit_shift[unit])) + " " + unit

# Tests and test results
>>> get_size("d:\\media\\bags of fun.avi")
'38 MB'
>>> get_size("d:\\media\\bags of fun.avi","KB")
'38,763 KB'
>>> get_size("d:\\media\\bags of fun.avi","kb")
'310,104 kb'

答案 6 :(得分:2)

这是我的两分钱,允许上下投射,并增加了可定制的精度:

def convertFloatToDecimal(f=0.0, precision=2):
    '''
    Convert a float to string of decimal.
    precision: by default 2.
    If no arg provided, return "0.00".
    '''
    return ("%." + str(precision) + "f") % f

def formatFileSize(size, sizeIn, sizeOut, precision=0):
    '''
    Convert file size to a string representing its value in B, KB, MB and GB.
    The convention is based on sizeIn as original unit and sizeOut
    as final unit. 
    '''
    assert sizeIn.upper() in {"B", "KB", "MB", "GB"}, "sizeIn type error"
    assert sizeOut.upper() in {"B", "KB", "MB", "GB"}, "sizeOut type error"
    if sizeIn == "B":
        if sizeOut == "KB":
            return convertFloatToDecimal((size/1024.0), precision)
        elif sizeOut == "MB":
            return convertFloatToDecimal((size/1024.0**2), precision)
        elif sizeOut == "GB":
            return convertFloatToDecimal((size/1024.0**3), precision)
    elif sizeIn == "KB":
        if sizeOut == "B":
            return convertFloatToDecimal((size*1024.0), precision)
        elif sizeOut == "MB":
            return convertFloatToDecimal((size/1024.0), precision)
        elif sizeOut == "GB":
            return convertFloatToDecimal((size/1024.0**2), precision)
    elif sizeIn == "MB":
        if sizeOut == "B":
            return convertFloatToDecimal((size*1024.0**2), precision)
        elif sizeOut == "KB":
            return convertFloatToDecimal((size*1024.0), precision)
        elif sizeOut == "GB":
            return convertFloatToDecimal((size/1024.0), precision)
    elif sizeIn == "GB":
        if sizeOut == "B":
            return convertFloatToDecimal((size*1024.0**3), precision)
        elif sizeOut == "KB":
            return convertFloatToDecimal((size*1024.0**2), precision)
        elif sizeOut == "MB":
            return convertFloatToDecimal((size*1024.0), precision)

根据需要添加TB等。

答案 7 :(得分:1)

UNITS = {1000: ['KB', 'MB', 'GB'],
            1024: ['KiB', 'MiB', 'GiB']}

def approximate_size(size, flag_1024_or_1000=True):
    mult = 1024 if flag_1024_or_1000 else 1000
    for unit in UNITS[mult]:
        size = size / mult
        if size < mult:
            return '{0:.3f} {1}'.format(size, unit)

approximate_size(2123, False)

答案 8 :(得分:0)

这是与 ls -lh 的输出匹配的版本。

def human_size(num: int) -> str:
    base = 1
    for unit in ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
        n = num / base
        if n < 9.95 and unit != 'B':
            # Less than 10 then keep 1 decimal place
            value = "{:.1f}{}".format(n, unit)
            return value
        if round(n) < 1000:
            # Less than 4 digits so use this
            value = "{}{}".format(round(n), unit)
            return value
        base *= 1024
    value = "{}{}".format(round(n), unit)
    return value

答案 9 :(得分:0)

这是我的实现方式:

from bisect import bisect

def to_filesize(bytes_num, si=True):
    decade = 1000 if si else 1024
    partitions = tuple(decade ** n for n in range(1, 6))
    suffixes = tuple('BKMGTP')

    i = bisect(partitions, bytes_num)
    s = suffixes[i]

    for n in range(i):
        bytes_num /= decade

    f = '{:.3f}'.format(bytes_num)

    return '{}{}'.format(f.rstrip('0').rstrip('.'), s)

它将最多打印三个小数,并去除尾随的零和句点。布尔参数si将切换基于10大小和基于2大小大小的使用。

这是它的对应物。它允许编写干净的配置文件,例如{'maximum_filesize': from_filesize('10M')。它返回一个近似于预期文件大小的整数。我没有使用移位,因为源值是一个浮点数(它可以接受from_filesize('2.15M')就好了)。将其转换为整数/十进制是可以的,但是会使代码更加复杂,并且已经可以正常使用了。

def from_filesize(spec, si=True):
    decade = 1000 if si else 1024
    suffixes = tuple('BKMGTP')

    num = float(spec[:-1])
    s = spec[-1]
    i = suffixes.index(s)

    for n in range(i):
        num *= decade

    return int(num)

答案 10 :(得分:0)

这里是:

def convert_bytes(size):
   for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
       if size < 1024.0:
           return "%3.1f %s" % (size, x)
       size /= 1024.0

   return size

答案 11 :(得分:0)

我想要2向转换,并且我想使用Python 3 format()支持来实现大多数pythonic。也许尝试datasize库模块? https://pypi.org/project/datasize/

$ pip install -qqq datasize
$ python
...
>>> from datasize import DataSize
>>> 'My new {:GB} SSD really only stores {:.2GiB} of data.'.format(DataSize('750GB'),DataSize(DataSize('750GB') * 0.8))
'My new 750GB SSD really only stores 558.79GiB of data.'

答案 12 :(得分:-1)

这是另一个版本的@ romeo反向实现,它处理单个输入字符串。

import re

def get_bytes(size_string):
    try:
        size_string = size_string.lower().replace(',', '')
        size = re.search('^(\d+)[a-z]i?b$', size_string).groups()[0]
        suffix = re.search('^\d+([kmgtp])i?b$', size_string).groups()[0]
    except AttributeError:
        raise ValueError("Invalid Input")
    shft = suffix.translate(str.maketrans('kmgtp', '12345')) + '0'
    return int(size) << int(shft)

答案 13 :(得分:-1)

类似于Aaron Duke的回复,但更多&#34; pythonic&#34; ;)

import re


RE_SIZE = re.compile(r'^(\d+)([a-z])i?b?$')

def to_bytes(s):
    parts = RE_SIZE.search(s.lower().replace(',', ''))
    if not parts:
        raise ValueError("Invalid Input")
    size = parts.group(1)
    suffix = parts.group(2)
    shift = suffix.translate(str.maketrans('kmgtp', '12345')) + '0'
    return int(size) << int(shift)

答案 14 :(得分:-1)

我是编程新手。我想出了以下函数,它将给定的文件大小转换为可读格式。

def file_size_converter(size):
    magic = lambda x: str(round(size/round(x/1024), 2))
    size_in_int = [int(1 << 10), int(1 << 20), int(1 << 30), int(1 << 40), int(1 << 50)]
    size_in_text = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    for i in size_in_int:
        if size < i:
            g = size_in_int.index(i)
            position = int((1024 % i) / 1024 * g)
            ss = magic(i)
            return ss + ' ' + size_in_text[position]

答案 15 :(得分:-2)

这适用于所有文件大小:

'factories' => [
    `Album\Controller\AlbumController` => `Album\Controller\Factory\AlbumControllerFactory`,
],