파일 크기의 사람을 읽을 수있는 버전을 얻기 위해 재사용 가능한 라이브러리?
-
11-09-2019 - |
문제
웹에는 바이트 크기에서 인간 읽기 가능한 크기를 반환 할 수있는 기능을 제공하는 다양한 스 니펫이 있습니다.
>>> human_readable(2048)
'2 kilobytes'
>>>
그러나 이것을 제공하는 파이썬 라이브러리가 있습니까?
해결책
간단한 구현으로 위의 "도서관을 요구하기에는 너무 작은 작업"문제를 해결합니다.
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)
지원 :
- 모두 현재 알려져 있습니다 이진 접두사
- 음수 및 양수
- 숫자는 1000 Yobibytes보다 큰 숫자
- 임의의 단위 (아마도 당신은 gibibits로 계산하는 것을 좋아할 것입니다!)
예시:
>>> sizeof_fmt(168963795964)
'157.4GiB'
~에 의해 프레드 시레라
다른 팁
당신이 찾고있는 것처럼 보이는 모든 기능을 가진 라이브러리는 humanize
. humanize.naturalsize()
당신이 찾고있는 모든 일을하는 것 같습니다.
여기 내 버전이 있습니다. for-loop를 사용하지 않습니다. 일정한 복잡성을 가지고 있습니다.1), 이론적으로 이론적으로 For-Loop를 사용하는 답변보다 더 효율적입니다.
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]
이 질문이 고대라는 것을 알고 있지만 최근에는 루프를 피하는 버전을 생각해 냈습니다. 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으로 간주 될 수 있습니다. :)
항상 그 사람들 중 하나가 있어야합니다. 오늘은 나야. 다음은 1 라이너 솔루션 또는 기능 서명을 계산하는 경우 두 줄입니다.
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
Django 설치를 사용하는 경우 시도해 볼 수도 있습니다 filesizeformat:
from django.template.defaultfilters import filesizeformat
filesizeformat(1073741824)
=>
"1.0 GB"
Python 3.6+의 다음 작품은 제 생각에 여기에서 답변을 이해하기가 가장 쉬우 며 사용 된 소수점 자리의 양을 사용자 정의 할 수 있습니다.
def human_readable_size(size, decimal_places=3):
for unit in ['B','KiB','MiB','GiB','TiB']:
if size < 1024.0:
break
size /= 1024.0
return f"{size:.{decimal_places}f}{unit}"
그러한 도서관 중 하나입니다 Hurry.FileSize.
>>> from hurry.filesize import alternative
>>> size(1, system=alternative)
'1 byte'
>>> size(10, system=alternative)
'10 bytes'
>>> size(1024, system=alternative)
'1 KB'
1000 또는 키비 바이트 보다 표준 친화적 일 것입니다.
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 (대문자) 접미사로 수천을 인쇄하는 라이브러리를 절대 신뢰하지 않습니다 :)
Hurry.filesize ()의 대안으로 제공된 스 니펫의 리프 핑, 여기에 사용 된 접두사를 기준으로 다양한 정밀 번호를 제공하는 스 니펫이 있습니다. 스 니펫만큼 간결하지는 않지만 결과가 마음에 듭니다.
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)
이것은 거의 모든 상황에서 필요한 것을 수행하고 선택적인 인수로 사용자 정의 할 수 있으며, 볼 수 있듯이 예쁜 많은 자체 문서 :
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'
이전의 모든 답변에서 벗어나, 여기에 내 테이크가 있습니다. 파일 크기를 바이트로 정수로 저장하는 객체입니다. 그러나 객체를 인쇄하려고하면 자동으로 사람이 읽을 수있는 버전이 나타납니다.
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)
나는 고정 정밀도를 좋아한다 Senderle 's Decimal 버전, 여기에는 위의 Joctee의 답변과 함께 그 하이브리드가 있습니다 (integer 비 기반으로 로그를받을 수 있다는 것을 알고 있습니까?) :
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')
"인간화"를 사용해야합니다.
>>> humanize.naturalsize(1000000)
'1.0 MB'
>>> humanize.naturalsize(1000000, binary=True)
'976.6 KiB'
>>> humanize.naturalsize(1000000, gnu=True)
'976.6K'
참조:
인간적인 우호적 인 프로젝트가 도움이됩니다 이것으로.
import humanfriendly
humanfriendly.format_size(1024)
위의 코드는 1KB를 답으로 제공합니다.
예 여기에서 찾을 수 있습니다.
diveintopython3도 있습니다 대화 이 기능에 대해.
현대 장고에는 자체 템플릿 태그가 있습니다 filesizeformat
:
a와 같은 값을 형식화합니다 human-readable
파일 크기 (예 : '13 kb ','4.1 mb ','102 바이트 '등).
예를 들어:
{{ value|filesizeformat }}
값이 123456789 인 경우 출력은 117.7MB입니다.
더 많은 정보: https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#filesizeformat
간단한 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])
후드 아래에서 작동하는 방법은 다음과 같습니다.
- 로그를 계산합니다2(파일 크기)
- 가장 가까운 유닛을 얻으려면 10으로 나눕니다. (예 : 크기가 5000 바이트 인 경우 가장 가까운 단위는
Kb
, 그래서 대답은 x kib이어야합니다) - 보고
file_size/value_of_closest_unit
유닛과 함께.
그러나 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의 배수입니다. 그것에 대해 더 자세히 설명합니다
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
아래에서 찾으려고하는 것은 결코 이미 게시 된 것 중에서 가장 성능이 좋거나 짧은 솔루션이 아닙니다. 대신, 그것은 초점을 맞 춥니 다 하나의 특별한 문제 다른 많은 대답은 그리워요.
즉 입력 할 때의 경우 999_995
주어진다 :
Python 3.6.1 ...
...
>>> value = 999_995
>>> base = 1000
>>> math.log(value, base)
1.999999276174054
가장 가까운 정수에 잘려서 입력에 다시 적용됩니다.
>>> order = int(math.log(value, base))
>>> value/base**order
999.995
이것은 우리가 통제해야 할 때까지 우리가 기대할 수있는 것 같습니다. 출력 정밀도. 그리고 이것은 상황이 조금 어려워지기 시작할 때입니다.
정밀도가 2 자리로 설정되어 있습니다.
>>> round(value/base**order, 2)
1000 # K
대신에 1M
.
어떻게 대응할 수 있습니까?
물론, 우리는 그것을 명시 적으로 확인할 수 있습니다.
if round(value/base**order, 2) == base:
order += 1
그러나 우리는 더 잘할 수 있습니까? 우리는 어떤 방법으로 알 수 있습니까? order
마지막 단계를 수행하기 전에 잘라야합니까?
우리가 할 수있는 것으로 밝혀졌습니다.
0.5 소수판 반올림 규칙을 가정하면 위의 if
조건은 다음으로 번역됩니다.
~를 야기하는
def abbreviate(value, base=1000, precision=2, suffixes=None):
if suffixes is None:
suffixes = ['', 'K', 'M', 'B', 'T']
if value == 0:
return f'{0}{suffixes[0]}'
order_max = len(suffixes) - 1
order = log(abs(value), base)
order_corr = order - int(order) >= log(base - 0.5/10**precision, base)
order = min(int(order) + order_corr, order_max)
factored = round(value/base**order, precision)
return f'{factored:,g}{suffixes[order]}'
기부
>>> abbreviate(999_994)
'999.99K'
>>> abbreviate(999_995)
'1M'
>>> abbreviate(999_995, precision=3)
'999.995K'
>>> abbreviate(2042, base=1024)
'1.99K'
>>> abbreviate(2043, base=1024)
'2K'
나타내다 Sridhar Ratnakumar
답변, 업데이트 :
def formatSize(sizeInBytes, decimalNum=1, isUnitWithI=False, sizeUnitSeperator=""):
"""format size to human readable string"""
# https://en.wikipedia.org/wiki/Binary_prefix#Specific_units_of_IEC_60027-2_A.2_and_ISO.2FIEC_80000
# K=kilo, M=mega, G=giga, T=tera, P=peta, E=exa, Z=zetta, Y=yotta
sizeUnitList = ['','K','M','G','T','P','E','Z']
largestUnit = 'Y'
if isUnitWithI:
sizeUnitListWithI = []
for curIdx, eachUnit in enumerate(sizeUnitList):
unitWithI = eachUnit
if curIdx >= 1:
unitWithI += 'i'
sizeUnitListWithI.append(unitWithI)
# sizeUnitListWithI = ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']
sizeUnitList = sizeUnitListWithI
largestUnit += 'i'
suffix = "B"
decimalFormat = "." + str(decimalNum) + "f" # ".1f"
finalFormat = "%" + decimalFormat + sizeUnitSeperator + "%s%s" # "%.1f%s%s"
sizeNum = sizeInBytes
for sizeUnit in sizeUnitList:
if abs(sizeNum) < 1024.0:
return finalFormat % (sizeNum, sizeUnit, suffix)
sizeNum /= 1024.0
return finalFormat % (sizeNum, largestUnit, suffix)
예제 출력은 다음과 같습니다.
def testKb():
kbSize = 3746
kbStr = formatSize(kbSize)
print("%s -> %s" % (kbSize, kbStr))
def testI():
iSize = 87533
iStr = formatSize(iSize, isUnitWithI=True)
print("%s -> %s" % (iSize, iStr))
def testSeparator():
seperatorSize = 98654
seperatorStr = formatSize(seperatorSize, sizeUnitSeperator=" ")
print("%s -> %s" % (seperatorSize, seperatorStr))
def testBytes():
bytesSize = 352
bytesStr = formatSize(bytesSize)
print("%s -> %s" % (bytesSize, bytesStr))
def testMb():
mbSize = 76383285
mbStr = formatSize(mbSize, decimalNum=2)
print("%s -> %s" % (mbSize, mbStr))
def testTb():
tbSize = 763832854988542
tbStr = formatSize(tbSize, decimalNum=2)
print("%s -> %s" % (tbSize, tbStr))
def testPb():
pbSize = 763832854988542665
pbStr = formatSize(pbSize, decimalNum=4)
print("%s -> %s" % (pbSize, pbStr))
def demoFormatSize():
testKb()
testI()
testSeparator()
testBytes()
testMb()
testTb()
testPb()
# 3746 -> 3.7KB
# 87533 -> 85.5KiB
# 98654 -> 96.3 KB
# 352 -> 352.0B
# 76383285 -> 72.84MB
# 763832854988542 -> 694.70TB
# 763832854988542665 -> 678.4199PB
이 솔루션은 마음의 작동 방식에 따라 다음과 같이 호소 할 수 있습니다.
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'