복붙노트

[PYTHON] 사람이 읽을 수있는 버전의 파일을 재사용 할 수있는 라이브러리?

PYTHON

사람이 읽을 수있는 버전의 파일을 재사용 할 수있는 라이브러리?

웹에는 바이트 크기에서 사람이 읽을 수있는 크기를 반환하는 함수를 제공하는 다양한 스 니펫이 있습니다.

>>> human_readable(2048)
'2 kilobytes'
>>>

그러나 이것을 제공하는 Python 라이브러리가 있습니까?

해결법

  1. ==============================

    1.간단한 구현으로 상기 "너무 작은 도서관 요구 과제"문제 해결 :

    간단한 구현으로 상기 "너무 작은 도서관 요구 과제"문제 해결 :

    def sizeof_fmt(num, suffix='B'):
        for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
            if abs(num) < 1024.0:
                return "%3.1f%s%s" % (num, unit, suffix)
            num /= 1024.0
        return "%.1f%s%s" % (num, 'Yi', suffix)
    

    지원 :

    예:

    >>> sizeof_fmt(168963795964)
    '157.4GiB'
    

    프레드시 레라

  2. ==============================

    2.찾고있는 모든 기능을 갖춘 라이브러리는 인간 답게 만들어졌습니다. humanize.naturalsize ()는 당신이 찾고있는 모든 것을하는 것처럼 보입니다.

    찾고있는 모든 기능을 갖춘 라이브러리는 인간 답게 만들어졌습니다. humanize.naturalsize ()는 당신이 찾고있는 모든 것을하는 것처럼 보입니다.

  3. ==============================

    3.여기 내 버전입니다. for 루프를 사용하지 않습니다. 그것은 일정한 복잡성, O (1)을 가지며 for 루프를 사용하는 여기의 답보다 이론적으로 더 효율적입니다.

    여기 내 버전입니다. for 루프를 사용하지 않습니다. 그것은 일정한 복잡성, O (1)을 가지며 for 루프를 사용하는 여기의 답보다 이론적으로 더 효율적입니다.

    from math import log
    unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 1, 2, 2, 2])
    def sizeof_fmt(num):
        """Human friendly file size"""
        if num > 1:
            exponent = min(int(log(num, 1024)), len(unit_list) - 1)
            quotient = float(num) / 1024**exponent
            unit, num_decimals = unit_list[exponent]
            format_string = '{:.%sf} {}' % (num_decimals)
            return format_string.format(quotient, unit)
        if num == 0:
            return '0 bytes'
        if num == 1:
            return '1 byte'
    

    무슨 일이 벌어지고 있는지 더 명확히하기 위해 문자열 형식에 대한 코드를 생략 할 수 있습니다. 실제로 작업을 수행하는 행은 다음과 같습니다.

    exponent = int(log(num, 1024))
    quotient = num / 1024**exponent
    unit_list[exponent]
    
  4. ==============================

    4.이 질문이 고대라는 것을 알고 있지만, 최근에 루프를 피하는 버전이 등장했습니다. log2를 사용하여 크기 순서를 결정하고 접미어 목록에 인덱스를 두 번 더합니다.

    이 질문이 고대라는 것을 알고 있지만, 최근에 루프를 피하는 버전이 등장했습니다. log2를 사용하여 크기 순서를 결정하고 접미어 목록에 인덱스를 두 번 더합니다.

    from math import log2
    
    _suffixes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
    
    def file_size(size):
        # determine binary order in steps of size 10 
        # (coerce to int, // still returns a float)
        order = int(log2(size) / 10) if size else 0
        # format file size
        # (.4g results in rounded numbers for exact matches and max 3 decimals, 
        # should never resort to exponent values)
        return '{:.4g} {}'.format(size / (1 << (order * 10)), _suffixes[order])
    

    그것의 가독성을 위해 unpythonic이라고 생각할 수 있습니다 :)

  5. ==============================

    5.그러한 라이브러리 중 하나는 서둘러. 파일 크기입니다.

    그러한 라이브러리 중 하나는 서둘러. 파일 크기입니다.

    >>> from hurry.filesize import alternative
    >>> size(1, system=alternative)
    '1 byte'
    >>> size(10, system=alternative)
    '10 bytes'
    >>> size(1024, system=alternative)
    '1 KB'
    
  6. ==============================

    6.Django를 설치했다면 filesizeformat을 시도해 볼 수도 있습니다 :

    Django를 설치했다면 filesizeformat을 시도해 볼 수도 있습니다 :

    from django.template.defaultfilters import filesizeformat
    filesizeformat(1073741824)
    
    =>
    
    "1.0 GB"
    
  7. ==============================

    7.1000 또는 kibibtes의 힘을 사용하는 것이보다 표준 친화적 일 것입니다 :

    1000 또는 kibibtes의 힘을 사용하는 것이보다 표준 친화적 일 것입니다 :

    def sizeof_fmt(num, use_kibibyte=True):
        base, suffix = [(1000.,'B'),(1024.,'iB')][use_kibibyte]
        for x in ['B'] + map(lambda x: x+suffix, list('kMGTP')):
            if -base < num < base:
                return "%3.1f %s" % (num, x)
            num /= base
        return "%3.1f %s" % (num, x)
    

    추신 수천 개의 K (대문자) 접미어를 가진 라이브러리를 신뢰하지 마십시오. :)

  8. ==============================

    8.hurry.filesize ()에 대한 대안으로 제공된 스 니펫에서 Riffing은 사용 된 접두사를 기반으로 다양한 정밀도 숫자를 제공하는 스 니펫입니다. 일부 발췌 내용만큼 간결하지는 않지만 결과가 마음에 든다.

    hurry.filesize ()에 대한 대안으로 제공된 스 니펫에서 Riffing은 사용 된 접두사를 기반으로 다양한 정밀도 숫자를 제공하는 스 니펫입니다. 일부 발췌 내용만큼 간결하지는 않지만 결과가 마음에 든다.

    def human_size(size_bytes):
        """
        format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB
        Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision
        e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc
        """
        if size_bytes == 1:
            # because I really hate unnecessary plurals
            return "1 byte"
    
        suffixes_table = [('bytes',0),('KB',0),('MB',1),('GB',2),('TB',2), ('PB',2)]
    
        num = float(size_bytes)
        for suffix, precision in suffixes_table:
            if num < 1024.0:
                break
            num /= 1024.0
    
        if precision == 0:
            formatted_size = "%d" % num
        else:
            formatted_size = str(round(num, ndigits=precision))
    
        return "%s %s" % (formatted_size, suffix)
    
  9. ==============================

    9.항상 그 사람들 중 하나가되어야합니다. 오늘은 나야. 한 줄짜리 솔루션이 있습니다. 함수 서명을 계산하면 두 줄입니다.

    항상 그 사람들 중 하나가되어야합니다. 오늘은 나야. 한 줄짜리 솔루션이 있습니다. 함수 서명을 계산하면 두 줄입니다.

    def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
        """ Returns a human readable string reprentation of bytes"""
        return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])
    

    >>> human_size(123)
    123 bytes
    >>> human_size(123456789)
    117GB
    
  10. ==============================

    10.이것은 거의 모든 상황에서 필요한 것을 할 것이고, 선택적 인수로 사용자 정의 할 수 있으며, 알 수 있듯이 거의 자체 문서화입니다.

    이것은 거의 모든 상황에서 필요한 것을 할 것이고, 선택적 인수로 사용자 정의 할 수 있으며, 알 수 있듯이 거의 자체 문서화입니다.

    from math import log
    def pretty_size(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']):
        pow,n=min(int(log(max(n*b**pow,1),b)),len(pre)-1),n*b**pow
        return "%%.%if %%s%%s"%abs(pow%(-pow-1))%(n/b**float(pow),pre[pow],u)
    

    예제 출력 :

    >>> pretty_size(42)
    '42 B'
    
    >>> pretty_size(2015)
    '2.0 KiB'
    
    >>> pretty_size(987654321)
    '941.9 MiB'
    
    >>> pretty_size(9876543210)
    '9.2 GiB'
    
    >>> pretty_size(0.5,pow=1)
    '512 B'
    
    >>> pretty_size(0)
    '0 B'
    

    고급 사용자 정의 :

    >>> pretty_size(987654321,b=1000,u='bytes',pre=['','kilo','mega','giga'])
    '987.7 megabytes'
    
    >>> pretty_size(9876543210,b=1000,u='bytes',pre=['','kilo','mega','giga'])
    '9.9 gigabytes'
    

    이 코드는 Python 2와 Python 3와 호환됩니다. PEP8 준수는 독자의 연습입니다. 기억하세요, 그것은 결과물입니다.

    최신 정보:

    수천 개의 쉼표가 필요하면 명백한 확장을 적용하십시오.

    def prettier_size(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']):
        r,f=min(int(log(max(n*b**pow,1),b)),len(pre)-1),'{:,.%if} %s%s'
        return (f%(abs(r%(-r-1)),pre[r],u)).format(n*b**pow/b**float(r))
    

    예 :

    >>> pretty_units(987654321098765432109876543210)
    '816,968.5 YiB'
    
  11. ==============================

    11.모든 이전 답변에서 그리기, 여기 그것에 걸릴 것입니다. 파일 크기를 정수로 바이트 단위로 저장하는 객체입니다. 그러나 개체를 인쇄하려고하면 자동으로 사람이 읽을 수있는 버전이 나타납니다.

    모든 이전 답변에서 그리기, 여기 그것에 걸릴 것입니다. 파일 크기를 정수로 바이트 단위로 저장하는 객체입니다. 그러나 개체를 인쇄하려고하면 자동으로 사람이 읽을 수있는 버전이 나타납니다.

    class Filesize(object):
        """
        Container for a size in bytes with a human readable representation
        Use it like this::
    
            >>> size = Filesize(123123123)
            >>> print size
            '117.4 MB'
        """
    
        chunk = 1024
        units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB']
        precisions = [0, 0, 1, 2, 2, 2]
    
        def __init__(self, size):
            self.size = size
    
        def __int__(self):
            return self.size
    
        def __str__(self):
            if self.size == 0: return '0 bytes'
            from math import log
            unit = self.units[min(int(log(self.size, self.chunk)), len(self.units) - 1)]
            return self.format(unit)
    
        def format(self, unit):
            if unit not in self.units: raise Exception("Not a valid file size unit: %s" % unit)
            if self.size == 1 and unit == 'bytes': return '1 byte'
            exponent = self.units.index(unit)
            quotient = float(self.size) / self.chunk**exponent
            precision = self.precisions[exponent]
            format_string = '{:.%sf} {}' % (precision)
            return format_string.format(quotient, unit)
    
  12. ==============================

    12.Sridhar Ratnakumar 솔루션에서 벗어나 조금 더 나아졌습니다. Python 3.6 이상에서 작동합니다.

    Sridhar Ratnakumar 솔루션에서 벗어나 조금 더 나아졌습니다. Python 3.6 이상에서 작동합니다.

    def human_readable_size(size, decimal_places):
        for unit in ['','KB','MB','GB','TB']:
            if size < 1024.0:
                break
            size /= 1024.0
        return f"{size:.{decimal_places}f}{unit}"
    
  13. ==============================

    13.나는 senderle의 십진수 버전의 고정밀도를 좋아한다. 위의 joctee의 대답과 함께 일종의 하이브리드가있다. (정수가 아닌베이스를 가지고 로그를 취할 수 있다는 것을 알고 있는가?) :

    나는 senderle의 십진수 버전의 고정밀도를 좋아한다. 위의 joctee의 대답과 함께 일종의 하이브리드가있다. (정수가 아닌베이스를 가지고 로그를 취할 수 있다는 것을 알고 있는가?) :

    from math import log
    def human_readable_bytes(x):
        # hybrid of https://stackoverflow.com/a/10171475/2595465
        #      with https://stackoverflow.com/a/5414105/2595465
        if x == 0: return '0'
        magnitude = int(log(abs(x),10.24))
        if magnitude > 16:
            format_str = '%iP'
            denominator_mag = 15
        else:
            float_fmt = '%2.1f' if magnitude % 3 == 1 else '%1.2f'
            illion = (magnitude + 1) // 3
            format_str = float_fmt + ['', 'K', 'M', 'G', 'T', 'P'][illion]
        return (format_str % (x * 1.0 / (1024 ** illion))).lstrip('0')
    
  14. ==============================

    14.DiveIntoPython3에서는이 함수에 대해서도 설명합니다.

    DiveIntoPython3에서는이 함수에 대해서도 설명합니다.

  15. ==============================

    15.방법에 대한 간단한 2 라이너 :

    방법에 대한 간단한 2 라이너 :

    def humanizeFileSize(filesize):
        p = int(math.floor(math.log(filesize, 2)/10))
        return "%.3f%s" % (filesize/math.pow(1024,p), ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'][p])
    

    후드에서 작동하는 방법은 다음과 같습니다.

    그러나 filesize가 0 또는 음수이면 (로그는 0 및 -ve 수에 대해 정의되지 않았기 때문에) 작동하지 않습니다. 추가 검사를 추가 할 수 있습니다.

    def humanizeFileSize(filesize):
        filesize = abs(filesize)
        if (filesize==0):
            return "0 Bytes"
        p = int(math.floor(math.log(filesize, 2)/10))
        return "%0.2f %s" % (filesize/math.pow(1024,p), ['Bytes','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'][p])
    

    예 :

    >>> humanizeFileSize(538244835492574234)
    '478.06 PiB'
    >>> humanizeFileSize(-924372537)
    '881.55 MiB'
    >>> humanizeFileSize(0)
    '0 Bytes'
    

    참고 - Kb와 KiB에는 차이가 있습니다. KB는 1000 바이트를 의미하지만 KiB는 1024 바이트를 의미합니다. KB, MB, GB는 모두 1000의 배수이며 KiB, MiB, GiB 등은 모두 1024의 배수입니다. 여기에 대한 자세한 내용

  16. ==============================

    16.

    def human_readable_data_quantity(quantity, multiple=1024):
        if quantity == 0:
            quantity = +0
        SUFFIXES = ["B"] + [i + {1000: "B", 1024: "iB"}[multiple] for i in "KMGTPEZY"]
        for suffix in SUFFIXES:
            if quantity < multiple or suffix == SUFFIXES[-1]:
                if suffix == SUFFIXES[0]:
                    return "%d%s" % (quantity, suffix)
                else:
                    return "%.1f%s" % (quantity, suffix)
            else:
                quantity /= multiple
    
  17. ==============================

    17.현대 Django에는 자체 템플릿 태그 filesizeat가 있습니다.

    현대 Django에는 자체 템플릿 태그 filesizeat가 있습니다.

    값을 사람이 읽을 수있는 파일 크기 (예 : '13 KB ','4.1 MB ','102 바이트 '등)로 형식화합니다.

    예 :

    {{ value|filesizeformat }}
    

    값이 123456789이면 출력은 117.7MB가됩니다.

    추가 정보 : https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#filesizeformat

  18. ==============================

    18."인간화"를 사용해야합니다.

    "인간화"를 사용해야합니다.

    >>> humanize.naturalsize(1000000)
    '1.0 MB'
    >>> humanize.naturalsize(1000000, binary=True)
    '976.6 KiB'
    >>> humanize.naturalsize(1000000, gnu=True)
    '976.6K'
    
  19. from https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size by cc-by-sa and MIT license