Skip to content

Commit

Permalink
feat(util.disk.get_file_size_fmt): Add human-readable formatter for f…
Browse files Browse the repository at this point in the history
…ile size.
  • Loading branch information
aaronmussig committed May 10, 2022
1 parent 6f9d1f5 commit d421cae
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/source/util/disk.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ Input/Output


.. autofunction:: magna.util.disk.move_file

.. autofunction:: magna.util.disk.get_file_size_fmt
21 changes: 21 additions & 0 deletions magna/util/disk.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,24 @@ def move_file(src: str, dest: str, checksum: Optional[bool] = False):
"""
copy_file(src, dest, checksum)
os.remove(src)


def get_file_size_fmt(path: str) -> str:
"""Format a bytes as a human-readable file unit.
Args:
path: The path to the file.
Returns:
The formatted file size.
References:
https://web.archive.org/web/20111010015624/http://blogmag.net/blog/read/38/Print_human_readable_file_size
"""
num = os.path.getsize(path)
suffix = 'B'
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"

0 comments on commit d421cae

Please sign in to comment.