title: Decode Base64 Gzip in python
body: <p>I'm trying to decode a gzip garmin activity file using Python. According to Garmin the file is a base64 gz file. I'm uploading the file from the browser via post and receiving the data in a Django App. </p>
  
  <p>The beginning of the file looks like this. </p>
  
  <blockquote>
    <p>begin-base64 644 data.xml.gz\nH4sIAAAAAAAAA y9a4 lx3Hn d6fguB7JzNuGZkNigNfdrAGbMAYaXeNfbPolXplYiRSIFu</p>
  </blockquote>
  
  <p>I've used the following code to adjust for padding and decode base64:</p>
  
  <pre><code>import base64
  padding_factor = (4 - len(data) % 4) % 4
  data += "="*padding_factor
  data_decoded = base64.b64decode(unicode(data).translate(dict(zip(map(ord, u'-_'), u'+/'))))
  </code></pre>
  
  <p>The beginning of data_decoded looks like this on the screen:</p>
  
  <blockquote>
    <p>\xe8"\x9f\xe6\xda\xb1\xee\xb8\xeb\x8e\x1dj\xd6\xb1\x9aX3\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03/Z\xe2\w\x1ewz~\x0b\x81\xec\x9c\xcd\xb8fd6(\r}\xda\xc0\x19\xb3\x00a\xa5\xde5\xf6\xcf\xa2U\xe9\x95\x88\x91H\x81n\xcb\xf7\xb4\x9f\xcc\xa7y%\xbd\x95\x9e\x13\xcd\x10\xf9Th\x04\x8d\xdf\xdf\xa6\xba\xa9\xcd\xf9=s\xf8G\xfc</p>
  </blockquote>
  
  <p><code>print data_decoded</code> looks like this:</p>
  
  <blockquote>
    <p>}???a??5?ϢU镈?H?n????̧y%?????Th??ߦ????=s?G?</p>
  </blockquote>
  
  <p>I then try to unzip the file using the following:</p>
  
  <pre><code>from cStringIO import StringIO
  from gzip import GzipFile
  sio = StringIO(data_decoded)
  gzf = gzip.GzipFile(fileobj=sio)
  guff = gzf.read()
  </code></pre>
  
  <p>After which I get the following error:</p>
  
  <pre><code>  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/gzip.py", line 245, in read
      self._read(readsize)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/gzip.py", line 287, in _read
      self._read_gzip_header()
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/gzip.py", line 181, in _read_gzip_header
      raise IOError, 'Not a gzipped file'
  IOError: Not a gzipped file
  </code></pre>
  
  <p>I also tried saving the file directly to disk and running gunzip from the command line and that also results in the same error. </p>
  
  <p>Any help would be much appreciated. </p>