title: python file I/O with binary data
body: <p>I'm extracting jpeg type bits from mp3 data actually it will be album arts.
  I thought about using library called mutagen, but I'd like to try with bits for some practice purpose.</p>
  
  <pre><code>import os
  import sys
  import re
  
  f = open(sys.argv[1], "rb")
  #sys.argv[1] gets mp3 file name ex) test1.mp3
  
  saver = ""
  for value in f:
      for i in value:
          hexval = hex(ord(i))[2:]
          if (ord(i) == 0):
              saver += "00" #to match with hex form
          else:
              saver += hexval
  
  
  header = "ffd8"
  tail = "ffd9"
  </code></pre>
  
  <p>this part of code is to get mp3 as bit form, and then transform it into hex
  and find jpeg trailers which starts as "ffd8" and ends with "ffd9"</p>
  
  <pre><code>frontmatch = re.search(header,saver)
  endmatch = re.search(tail, saver)
  startIndex = frontmatch.start()
  endIndex = endmatch.end()
  
  jpgcontents = saver[startIndex:endIndex]
  scale = 16 # equals to hexadecimal
  numbits = len(jpgcontents) * 4 #log2(scale)
  bitcontents = bin(int(jpgcontents, scale))[2:].zfill(numbits)
  </code></pre>
  
  <p>and here, I get the bits between the header and tail and transform it into
  binary form. Which supposed to be the jpg part of the mp3 files.</p>
  
  <pre><code>txtfile = open(sys.argv[1] + "_tr.jpg", "w")
  txtfile.write(bitcontents)
  </code></pre>
  
  <p>and I wrote the bin to the new file with writing type as jpg.
  sorry for my wrong naming as txtfile.</p>
  
  <p>But these codes gave the error which is</p>
  
  <pre><code>Error interpreting JPEG image file
  (Not a JPEG file: starts with 0x31 0x31)
  </code></pre>
  
  <p>I'm not sure whether the bits I extracted are wrong or writing to the file
  step is wrong. Or there might be other problem in code.</p>
  
  <p>I'm working in linux version with python 2.6. Is there anything wrong with 
  just writing str type of bin data as JPG?</p>