title: to parse a file with text (with offset information) and binary data in python
body: <p>I have an xml file, which contains a set of textual element tags (each contains the decimal offset value and data length of the corresponding binary element) and the whole binary data of all the elements at the end. An example is as follows.</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;Package&gt;
    &lt;element&gt;
          &lt;offset&gt;0&lt;/offset&gt;
          &lt;length&gt;2961181&lt;/length&gt;
          &lt;checksum&gt;4238515972&lt;/checksum&gt;
          &lt;format&gt;gzip&lt;/format&gt;
    &lt;/element&gt;
    &lt;element&gt;
          &lt;offset&gt;2961181&lt;/offset&gt;
          &lt;length&gt;5442&lt;/length&gt;
          &lt;checksum&gt;4238515972&lt;/checksum&gt;
          &lt;format&gt;bin&lt;/format&gt;
    &lt;/element&gt;
  &lt;/Package&gt;
  BINARY_DATA
  </code></pre>
  
  <p>please note, the offset is decimal and counts from the first byte after the headers.
  How can I parse this file in python, grab the corresponding element based on the offset, uncompressed it (if its format is gzip) and store it as a file?</p>
  
  <p>well, based on the replies from OmnipotentEntity and Jakob_B, I made the following short script, just to see if it works for the 1st element:</p>
  
  <pre><code>import zlib
  
  f = open("file.xml", "r")
  text = f.read()
  position = text.find("&lt;/Package&gt;\n")
  headerSize=position+ len("&lt;/Package&gt;\n") + 1 
  offset=0
  f.seek(headerSize + offset) 
  length = 2961181
  bin_data = f.read(length)
  zipped=1
  if (zipped):
    ungziped_str = zlib.decompressobj().decompress('x\x9c' + bin_data)
    print(ungziped_str)
  f.close()
  </code></pre>
  
  <p>however, I got the following error:</p>
  
  <p>Traceback (most recent call last):
    File "file_parse.py", line 11, in ?
      ungziped_str = zlib.decompressobj().decompress('x\x9c' + bin_data)
  zlib.error: Error -3 while decompressing: invalid block type</p>
  
  <p>what is the problem? the input file is incorrect, or the code is incorrect? </p>