Skip to content

Instantly share code, notes, and snippets.

@jamescherti
Last active December 25, 2022 22:07
Show Gist options
  • Save jamescherti/b8badae104576edc082f5095bfe0652f to your computer and use it in GitHub Desktop.
Save jamescherti/b8badae104576edc082f5095bfe0652f to your computer and use it in GitHub Desktop.
A python method that returns the human-readable size of a file.
#!/usr/bin/env python
# Author: James Cherti
# License: MIT
# URL: https://gist.github.com/jamescherti/b8badae104576edc082f5095bfe0652f
"""Return the human-readable size of a file."""
from typing import Union
def human_readable_file_size(file_size: Union[int, float]) -> str:
"""Return the human-readable size of a file."""
for unit in ["", "Kb", "Mb", "Gb", "Tb"]:
if file_size < 1024.0:
return "{:g} {}".format(round(file_size, 1), unit)
file_size = file_size / 1024.0
return str(file_size)
def main():
"""Test human_readable_file_size()."""
print(human_readable_file_size(1023))
print(human_readable_file_size(1024))
print(human_readable_file_size(1024 + 512))
print(human_readable_file_size(1024 * 1024))
print(human_readable_file_size(1024 * 1024 * 1024))
print(human_readable_file_size(1024 * 1024 * 1024 * 1024))
if __name__ == '__main__':
main()
@jamescherti
Copy link
Author

jamescherti commented Jun 28, 2021

Output:

1023
1 Kb
1.5 Kb
1 Mb
1 Gb
1 Tb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment