-
-
Save matschundbrei/fe14fe5d0ebbe6d1fd4d10bd0f35508e to your computer and use it in GitHub Desktop.
Python function to convert a human-readable byte string (e.g. 2G, 10GB, 30MB, 20KB) to a number of bytes
This file contains hidden or 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
# stolen from https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float | |
def is_number(s): | |
""" | |
tries to convert to float and returns true if it works | |
""" | |
try: | |
float(s) | |
return True | |
except ValueError: | |
return False | |
def human_readable_to_bytes(size): | |
""" | |
Given a human-readable byte string (e.g. 2G, 10GB, 30MB, 20KB), | |
return the number of bytes. Will return 0 if the argument has | |
unexpected form. | |
maub: I've made this new version for py3 and for abbreviations in the | |
real world, that might use floats (in my case: df under linux) | |
""" | |
if size[-1] == 'B': | |
size = size[:-1] | |
if is_number(size): | |
bytes = float(size) | |
else: | |
bytes = size[:-1] | |
unit = size[-1] | |
if is_number(bytes): | |
bytes = float(bytes) | |
if unit == 'G': | |
bytes *= 1073741824 | |
elif unit == 'M': | |
bytes *= 1048576 | |
elif unit == 'K': | |
bytes *= 1024 | |
else: | |
bytes = 0 | |
else: | |
bytes = 0 | |
return int(bytes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment