title: Python: row_type() causes error when trying to read specific columns in csv file
body: <p>I am trying to use this helper function (which I found on StackOverflow) to help me read rows of a csv file, but only keeping certain columns from the original file. </p>
  
  <pre><code>def read_csv(file, columns, type_name="Row"):
      try:
          row_type = namedtuple(type_name, columns)
      except ValueError:
          row_type = tuple
      rows = iter(csv.reader(file))
      header = rows.next()
      mapping = [header.index(x) for x in columns]
      for row in rows:
          row = row_type(*[row[i] for i in mapping])
          yield row
  </code></pre>
  
  <p>Now the code that I have written using this function opens two files, a key file and a responses file, and grades the responses in the questions.csv in two separate categories, x and y, using the key found in the file answers.csv.</p>
  
  <pre><code>x = ["q1","q4","q5","q7","q9"]
  y = ["q2","q3","q6","q8","q10"]
  
  key = open('answers.csv','rU')
  for row in read_csv(key, x):
     x_answers = row
     print x_answers
  key.close()
  
  key = open('answers.csv','rU')
  for row in read_csv(key, y):
      y_answers = row
      print y_answers
  key.close()
  
  responses = open('questions.csv', 'rU')
  for row in read_csv(responses, x):
      print row
  responses.close()
  
  responses = open('questions.csv', 'rU')
  for row in read_csv(responses, y):
      print row
  responses.close()
  </code></pre>
  
  <p>For now I'm just printing the extracted rows from the two files seperated into the two categories and I get this error when the program gets to the last for loop:</p>
  
  <pre><code>execfile("read_csv.py")
  Row(q1='b', q4='c', q5='c', q7='b', q9='d')
  Row(q2='d', q3='c', q6='b', q8='b', q10='b')
  Row(q1='b', q4='c', q5='c', q7='c', q9='d')
  Row(q1='b', q4='c', q5='c', q7='b', q9='d')
  Row(q1='b', q4='c', q5='c', q7='b', q9='d')
  Row(q1='b', q4='c', q5='c', q7='b', q9='d')
  Row(q1='b', q4='c', q5='c', q7='b', q9='d')
  Traceback (most recent call last):
      File "&lt;stdin&gt;", line 1, in &lt;module&gt;
      File "read_csv.py", line 52, in &lt;module&gt;
          for row in read_csv(responses, US):
      File "read_csv.py", line 20, in read_csv
          row = row_type(*[row[i] for i in mapping])
      IndexError: list index out of range
  </code></pre>
  
  <p>I don't understand why the index out of range is given because the for loop is an exact copy of the previous for loop and I made sure to reopened the file so the cursor is in the beginning. </p>