22
33
44def file_size (
5- value : int , binary : bool = False , gnu : bool = False , formatting : str = ".1f"
5+ value : int , binary : bool = False , gnu : bool = False , formatting : str = ".1f" , small_formatting : str = "" ,
66) -> str :
77 """Return human-readable file size.
88
@@ -12,12 +12,16 @@ def file_size(
1212 `10**3`. If ``gnu`` is True, the binary argument is ignored and GNU-style
1313 (``ls -sh`` style) prefixes are used (K, M) with the `2**10` definition.
1414 Non-gnu modes are compatible with jinja2's ``filesizeformat`` filter.
15+ small_formatting is used instead of formatting when the number of bytes
16+ is small enough that the applied suffix is B / Byte / Bytes, since files
17+ cannot have a decimal number of bytes in a file size
1518
1619 Args:
1720 value: size number.
1821 binary: binary format. Defaults to False.
1922 gnu: GNU format. Defaults to False.
2023 formatting: format pattern. Defaults to ".1f".
24+ small_formatting: format pattern for small values. Defaults to "".
2125
2226 Returns:
2327 str: file size in natural language.
@@ -30,18 +34,19 @@ def file_size(
3034 suffixes = (" kB" , " MB" , " GB" , " TB" , " PB" , " EB" , " ZB" , " YB" )
3135
3236 base = 1024 if (gnu or binary ) else 1000
37+ fmt = small_formatting if value < base else formatting
3338
3439 if value == 1 and not gnu :
35- return f"{ 1 :{formatting }} Byte"
40+ return f"{ 1 :{fmt }} Byte"
3641 if value < base and not gnu :
37- return f"{ value :{formatting }} Bytes"
42+ return f"{ value :{fmt }} Bytes"
3843 if value < base and gnu :
39- return f"{ value :{formatting }} B"
44+ return f"{ value :{fmt }} B"
4045
4146 byte_size = float (value )
4247 suffix = ""
4348 for i , suffix in enumerate (suffixes ):
4449 unit = base ** (i + 2 )
4550 if byte_size < unit :
46- return f"{ base * byte_size / unit :{formatting }} { suffix } "
47- return f"{ base * byte_size / unit :{formatting }} { suffix } "
51+ return f"{ base * byte_size / unit :{fmt }} { suffix } "
52+ return f"{ base * byte_size / unit :{fmt }} { suffix } "
0 commit comments