ByteSize takes the pain out of data-size conversions—efficiently handle metric/binary units, block alignment, and more, all from a single, Pythonic interface.
ByteSize is a Python library that simplifies operations with file sizes, offering dynamic unit conversions, string parsing, formatting, and more.
- Parse human-readable size strings (e.g.,
"10MB","1.5GiB") into raw bytes. - Convert between metric (e.g.,
MB) and binary units (e.g.,MiB). - Arithmetic operations while preserving byte units.
- Block-aligned size calculations.
- User-friendly formatting with customizable precision.
- No dependencies, lightweight, and easy to use.
Clone the repository and install the package:
pip install pybytesizeCreate a ByteSize object from integers or human-readable strings.
By default, string representation will find the most suitable (binary) unit.
>>> from bytesize import ByteSize
>>> size = ByteSize(1_048_576) # From an integer bytes
>>> print(size)
1.00 MiB
>>> size = ByteSize("1_073_741_824MB") # From a string
>>> print(size)
1.00 PiBAccess size in different units dynamically.
>>> size1 = ByteSize(1_073_741_824)
>>> print(size1.MB) # Metric:
1.073741824
>>> print(size1.MiB) # Binary
1.00Calculate the apparent size with block alignment.
>>> size = ByteSize(123_456_789)
>>> aligned_size = size.apparent_size(4096)
>>> print(aligned_size.bytes)
123457536Perform addition, subtraction, multiplication, and division.
>>> size3 = ByteSize("1GB") + ByteSize("512MB")
>>> print(size3) # '1.50 GiB'
1.50 GiB
>>> size4 = ByteSize("1TB") - ByteSize("500GB")
>>> print(size4) # '0.50 TiB'
0.50 TiBCustomize formatting for specific units or precision.
>>> size = ByteSize(123_456_789)
>>> print(f"{size:.2f:MB}") # '123.46 MB'
123.46 MB
>>> print(f"{size:.2f:GiB}") # '0.11 GiB'
0.11 GiB