Skip to content

Instantly share code, notes, and snippets.

@wkettler
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkettler/9238305 to your computer and use it in GitHub Desktop.
Save wkettler/9238305 to your computer and use it in GitHub Desktop.
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