title: Using Python, how do I to read/write data in memory like I would with a file?
body: <p>I'm used to C++, and I build my data handling classes/functions to handle stream objects instead of files. I'd like to know how I might modify the following code, so that it can handle a stream of binary data in memory, rather than a file handle.</p>
  
  <pre><code>def get_count(self):
      curr = self.file.tell()
      self.file.seek(0, 0)
      count, = struct.unpack('I', self.file.read(c_uint32_size))
      self.file.seek(curr, 0)
      return count
  </code></pre>
  
  <p>In this case, the code assumes <code>self.file</code> is a file, opened like so:</p>
  
  <pre><code>file = open('somefile.data, 'r+b')
  </code></pre>
  
  <p>How might I use the same code, yet instead do something like this:</p>
  
  <pre><code>file = get_binary_data()
  </code></pre>
  
  <p>Where <code>get_binary_data()</code> returns a string of binary data. Although the code doesn't show it, I also need to write to the stream (I didn't think it was worth posting the code for that).</p>
  
  <p>Also, if possible, I'd like the new code to handle files as well.</p>