title: Is there an elegant way to use struct and namedtuple instead of this?
body: <p>I'm reading a binary file made up of records that in C would look like this:</p>
  
  <pre><code>typedef _rec_t
  {
    char text[20];
    unsigned char index[3];
  } rec_t;
  </code></pre>
  
  <p>Now I'm able to parse this into a tuple with 23 distinct values, but would prefer if I could use <code>namedtuple</code> to combine the first 20 bytes into <code>text</code> and the three remaining bytes into <code>index</code>. How can I achieve that? Basically instead of one tuple of 23 values I'd prefer to have two tuples of 20 and 3 values respectively and access these using a "natural name", i.e. by means of <code>namedtuple</code>.</p>
  
  <p>I am currently using the format <code>"20c3B"</code> for <code>struct.unpack_from()</code>.</p>
  
  <p>Note: There are many consecutive records in the string when I call <code>parse_text</code>.</p>
  
  <hr>
  
  <p>My code (stripped down to the relevant parts):</p>
  
  <pre><code>#!/usr/bin/env python
  import sys
  import os
  import struct
  from collections import namedtuple
  
  def parse_text(data):
      fmt = "20c3B"
      l = len(data)
      sz = struct.calcsize(fmt)
      num = l/sz
      if not num:
          print "ERROR: no records found."
          return
      print "Size of record %d - number %d" % (sz, num)
      #rec = namedtuple('rec', 'text index')
      empty = struct.unpack_from(fmt, data)
      # Loop through elements
      # ...
  
  def main():
      if len(sys.argv) &lt; 2:
          print "ERROR: need to give file with texts as argument."
          sys.exit(1)
      s = os.path.getsize(sys.argv[1])
      f = open(sys.argv[1])
      try:
          data = f.read(s)
          parse_text(data)
      finally:
          f.close()
  
  if __name__ == "__main__":
      main()
  </code></pre>