parse_size

pyhelpers.ops.parse_size(size, binary=True, precision=1)

Parse size from / into readable format of bytes.

Parameters
  • size (str or int or float) – human- or machine-readable format of size

  • binary (bool) – whether to use binary (i.e. factorized by 1024) representation, defaults to True; if binary=False, use the decimal (or metric) representation (i.e. factorized by 10 ** 3)

  • precision (int) – number of decimal places (when converting size to human-readable format), defaults to 1

Returns

parsed size

Return type

int or str

Examples:

>>> from pyhelpers.ops import parse_size

>>> parse_size(size='123.45 MB')
129446707

>>> parse_size(size='123.45 MB', binary=False)
123450000

>>> parse_size(size='123.45 MiB', binary=True)
129446707
>>> # If a metric unit (e.g. 'MiB') is specified in the input,
>>> # the function returns a result accordingly, no matter whether `binary` is True or False
>>> parse_size(size='123.45 MiB', binary=False)
129446707

>>> parse_size(size=129446707, precision=2)
'123.45 MiB'

>>> parse_size(size=129446707, binary=False, precision=2)
'129.45 MB'