Original code copyright (C) 2009-2022 Rudolf Cardinal (

This file is part of cardinal_pythonlib.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

cardinal_pythonlib.sizeformatter.bytes2human(n: int | float, format: str = '%(value).1f %(symbol)s', symbols: str = 'customary') str[source]

Converts a number of bytes into a human-readable format. From

  • n – number of bytes

  • format – a format specification string

  • symbols – can be one of "customary", "customary_ext", "iec" or "iec_ext"; see


the formatted number


>>> bytes2human(0)
'0.0 B'
>>> bytes2human(0.9)
'0.0 B'
>>> bytes2human(1)
'1.0 B'
>>> bytes2human(1.9)
'1.0 B'
>>> bytes2human(1024)
'1.0 K'
>>> bytes2human(1048576)
'1.0 M'
>>> bytes2human(1099511627776127398123789121)
'909.5 Y'
>>> bytes2human(9856, symbols="customary")
'9.6 K'
>>> bytes2human(9856, symbols="customary_ext")
'9.6 kilo'
>>> bytes2human(9856, symbols="iec")
'9.6 Ki'
>>> bytes2human(9856, symbols="iec_ext")
'9.6 kibi'
>>> bytes2human(10000, "%(value).1f %(symbol)s/sec")
'9.8 K/sec'
>>> # precision can be adjusted by playing with %f operator
>>> bytes2human(10000, format="%(value).5f %(symbol)s")
'9.76562 K'
cardinal_pythonlib.sizeformatter.human2bytes(s: str) int[source]

Modified from

Attempts to guess the string format based on default symbols set and return the corresponding bytes as an integer. When unable to recognize the format, ValueError is raised.

>>> human2bytes('0 B')
>>> human2bytes('1 K')
>>> human2bytes('1 M')
>>> human2bytes('1 Gi')
>>> human2bytes('1 tera')
>>> human2bytes('0.5kilo')
>>> human2bytes('0.1  byte')
>>> human2bytes('1 k')  # k is an alias for K
>>> human2bytes('12 foo')
Traceback (most recent call last):
ValueError: can't interpret '12 foo'
cardinal_pythonlib.sizeformatter.sizeof_fmt(num: float, suffix: str = 'B') str[source]

Formats a number of bytes in a human-readable binary format (e.g. 2048 becomes '2 KiB'); from