title: Filtering a CSV file in python
body: <p>I have downloaded this <a href="http://www.ncbi.nlm.nih.gov/gv/mhc/ihwg.cgi?cmd=page&amp;user_id=0&amp;probe_id=0&amp;source_id=0&amp;locus_id=0&amp;locus_group=1&amp;proto_id=0&amp;kit_id=0&amp;page=RAmain" rel="nofollow">csv file</a>, which creates a spreadsheet of gene information. What is important is that in the <code>HLA-*</code> columns, there is gene information. If the gene is too low of a resolution e.g. <code>DQB1*03</code> then the row should be deleted. If the data is too high resoltuion e.g. <code>DQB1*03:02:01</code>, then the <code>:01</code> tag at the end needs to be removed. So, ideally I want to proteins to be in the format <code>DQB1*03:02</code>, so that it has two levels of resolution after <code>DQB1*</code>. How can I tell python to look for these formats, and ignore the data stored in them.
  e.g.<br></p>
  
  <pre><code>if (csvCell is of format DQB1*03:02:01):
     delete the :01 # but do this in a general format
  elif (csvCell is of format DQB1*03):
     delete row
  else:
     goto next line
  </code></pre>
  
  <p>UPDATE: Edited code I referenced</p>
  
  <pre><code>import csv
  import re
  import sys
  
  csvdictreader = csv.DictReader(open('mhc.csv','r+b'), delimiter=',')
  csvdictwriter = csv.DictWriter(file('mhc_fixed.csv','r+b'), fieldnames=csvdictreader.fieldnames, delimiter=',')
  csvdictwriter.writeheader()
  targets = [name for name in csvdictreader.fieldnames if name.startswith('HLA-D')]
  
  for rowfields in csvdictreader:
    keep = True
    for field in targets:
      value = rowfields[field]
      if re.match(r'^\w+\*\d\d$', value):
        keep = False
        break # quit processing target fields
      elif re.match(r'^(\w+)\*(\d+):(\d+):(\d+):(\d+)$', value):
        rowfields[field] = re.sub(r'^(\w+)\*(\d+):(\d+):(\d+):(\d+)$',r'\1*\2:\3', value)
      else: # reduce gene resolution if too high
                # by only keeping first two alles if three are present
        rowfields[field] = re.sub(r'^(\w+)\*(\d+):(\d+):(\d+)$',r'\1*\2:\3', value)
    if keep:
       csvdictwriter.writerow(rowfields)
  </code></pre>