Last active
August 29, 2015 13:56
-
-
Save wkettler/9238305 to your computer and use it in GitHub Desktop.
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
import re | |
def to_bytes(value): | |
""" | |
Convert a size string with an exponent into bytes. | |
Input: | |
value (str): Size string | |
Output: | |
bytes (int): Size in bytes | |
""" | |
units = [ 'B', 'K', 'M', 'G', 'T', 'P', 'E' ] | |
# Match any floating point number followed by an optional unit | |
m = re.search(r'^([0-9]*\.?[0-9]+)([%s])?b?$' % ''.join(units), value, re.IGNORECASE) | |
if not m: | |
raise ValueError('invalid format %s' % value) | |
num = float(m.group(1)) | |
if m.group(2): | |
unit = m.group(2).upper() | |
else: | |
unit = 'B' | |
# Perform byte calculation | |
exp = units.index(unit) | |
byte = num * 1024 ** exp | |
return byte |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment