Last active
December 25, 2022 22:07
-
-
Save jamescherti/b8badae104576edc082f5095bfe0652f to your computer and use it in GitHub Desktop.
A python method that returns the human-readable size of a file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: