title: Python "with" statement syntax
body: <p>I have some python code that parse the csv file. Now our vendor decide to change the data file to gzip csv file. I was wondering what's the minimal/cleanest code change I have to make. Current function:</p>
  
  <pre><code>def load_data(fname, cols=()):
      ... ...
      with open(fname) as f:
          reader = csv.DictReader(f)
          ... ... 
  </code></pre>
  
  <p>I don't want to duplicate the code to load_data2(), and change the with statement to, thought it works perfectly.</p>
  
  <pre><code>with gzip.open(fname) as f:
  </code></pre>
  
  <p>How can I factor out the with statement? </p>
  
  <pre><code>def load_data(fname, cols=()):
      ... ...
      if fname.endswith('.csv.gz'):
          with gzip.open(fname) as f:
      else:
          with open(fname) as f:
  
          reader = csv.DictReader(f)
          ... ... # code to parse
  </code></pre>