How to write output file in CSV format in python?
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p>

<p>Getting error in Python 3.5:</p>

<pre><code>wr.writerow(var)
TypeError: a bytes-like object is required, not 'str'
</code></pre>

<p>and </p>

<p>In Python 2.7, I am getting all column result in one column. </p>

<p>Expected Result:<br>
An output file same format as the input file.</p>

<p>Code:</p>

<pre><code>import csv

f1 = open("input_1.csv", "r") 

resultFile = open("out.csv", "wb")
wr = csv.writer(resultFile, quotechar=',') 

def sort_duplicates(f1):
  for i in range(0, len(f1)):
      f1.insert(f1.index(f1[i])+1, f1[i])
      f1.pop(i+1)

for var in f1:
      #print (var)
      wr.writerow([var]) 
</code></pre>

<p>If I am using <code>resultFile = open("out.csv", "w")</code>, I get one row extra in the output file. </p>

<p>If I am using above code, getting one row and column extra.</p>

<p>On Python 3, <code>csv</code> <em>requires</em> that you open the file in text mode, not binary mode. Drop the <code>b</code> from your file mode. You should really use <code>newline=''</code> too:</p>

<pre><code>resultFile = open("out.csv", "w", newline='')
</code></pre>

<p>Better still, use the file object as a context manager to ensure it is closed automatically:</p>

<pre><code>with open("input_1.csv", "r") as f1, \
     open("out.csv", "w", newline='') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    for var in f1:
        wr.writerow([var.rstrip('\n')])
</code></pre>

<p>I've also <em>stripped</em> the lines from <code>f1</code> (just to remove the newline) and put the line in a list; <code>csv.writer.writerow</code> wants a sequence with columns, not a single string.</p>

<p>Quoting the <a href="https://docs.python.org/3/library/csv.html#csv.writer" rel="nofollow"><code>csv.writer()</code> documentation</a>:</p>

<blockquote>
  <p>If <em>csvfile</em> is a file object, it should be opened with <code>newline=''</code> [1]. <em>[...]</em> All other non-string data are stringified with <code>str()</code> before being written.</p>
  
  <p>[1] If <code>newline=''</code> is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use <code>\r\n</code> linendings on write an extra <code>\r</code> will be added. It should always be safe to specify <code>newline=''</code>, since the csv module does its own (<a href="https://docs.python.org/3/glossary.html#term-universal-newlines" rel="nofollow">universal</a>) newline handling.</p>
</blockquote>

python csv