Coverage for pyguymer3/convert_pretty_bytes_to_bytes.py: 47%
19 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
1#!/usr/bin/env python3
3# Define function ...
4def convert_pretty_bytes_to_bytes(
5 prettyString : str,
6 /,
7) -> float:
8 """Convert a pretty string of a bytes with some units to a value of bytes
10 This function reads in a string of a human-readable value of bytes with some
11 units and returns the same value as a float.
13 Parameters
14 ----------
15 prettyString : str
16 the human-readable value of bytes with some units
18 Returns
19 -------
20 prettySize : float
21 the value of bytes
23 Notes
24 -----
25 Copyright 2017 Thomas Guymer [1]_
27 References
28 ----------
29 .. [1] PyGuymer3, https://github.com/Guymer/PyGuymer3
31 Examples
32 --------
33 >>> pyguymer3.convert_pretty_bytes_to_bytes("1.5 KiB")
34 1536.0
36 """
38 # Import standard modules ...
39 import re
41 # Extract digits (with decimal point) and letters separately ...
42 prettySize : float = float(re.sub(r"[a-zA-Z]", "", prettyString).strip()) # [?]
43 units : str = re.sub(r"[0-9\.]", "", prettyString).strip()
45 # Check what the units are and return it scaled ...
46 match units:
47 case "B":
48 return prettySize
49 case "KB" | "KiB":
50 return 1024.0 * prettySize
51 case "MB" | "MiB":
52 return 1024.0 * 1024.0 * prettySize
53 case "GB" | "GiB":
54 return 1024.0 * 1024.0 * 1024.0 * prettySize
55 case "TB" | "TiB":
56 return 1024.0 * 1024.0 * 1024.0 * 1024.0 * prettySize
57 case "PB" | "PiB":
58 return 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0 * prettySize
59 case _:
60 # Crash ...
61 raise ValueError(f"\"units\" is an unexpected value ({repr(units)})") from None