title: Writing a .CSV file in Python that works for both Python 2.7+ and Python 3.3+ in Windows
body: <p>EDIT: I put it in the title, but just realized I didn't mention it in the body. This seems to be specific to Windows.</p>
  
  <p>I'm having a hard time writing output using the <code>csv</code> Python module in a script that works with both Python 2.7 and 3.3.</p>
  
  <p>First try which works as expected in Python 2.7:</p>
  
  <pre><code>with open('test.csv', 'wb') as csv_file:
      writer = csv.DictWriter(csv_file, ['header1', 'header2'])
      writer.writeheader()
      for item in items:
          writer.writerow(item)
  </code></pre>
  
  <p>However, when that same thing is run in Python 3.3 you wind up with:</p>
  
  <pre><code>TypeError: 'str' does not support the buffer interface
  </code></pre>
  
  <p>So I change <code>'wb'</code> to <code>'wt'</code> and it runs, but now I have an extra blank row every other line in the file.</p>
  
  <p>To fix that, I change:</p>
  
  <pre><code>with open('test.csv', 'wt') as csv_file:
  </code></pre>
  
  <p>to:</p>
  
  <pre><code>with open('test.csv', 'wt', newline='') as csv_file:
  </code></pre>
  
  <p>But now, it breaks Python 2.7:</p>
  
  <pre><code>TypeError: 'newline' is an invalid keyword argument for this function
  </code></pre>
  
  <p>I know I could just do something like:</p>
  
  <pre><code>try:
      with open('test.csv', 'wt', newline='') as csv_file:
          writer = csv.DictWriter(csv_file, ['header1', 'header2'])
          writer.writeheader()
          for item in items:
              writer.writerow(item)
  except TypeError:
      with open('test.csv', 'wb') as csv_file:
          writer = csv.DictWriter(csv_file, ['header1', 'header2'])
          writer.writeheader()
          for item in items:
              writer.writerow(item)
  </code></pre>
  
  <p>However, that has some seriously bad duplication.</p>
  
  <p>Does anyone have a cleaner way of doing this?</p>
  
  <p>EDIT: The test data is simple and has no newlines or anything:</p>
  
  <pre><code>items = [{'header1': 'value', 'header2': 'value2'},
           {'header1': 'blah1', 'header2': 'blah2'}]
  </code></pre>