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>Others have answered that you should open the output file in text mode when using Python 3, i.e.</p>

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

<p>But you also need to parse the incoming CSV data. As it is your code reads each line of the input CSV file as a single string. Then, without splitting that line into its constituent fields, it passes the string to the CSV writer. As a result, the <code>csv.writer</code> will treat the string as a sequence and output each <em>character</em> , including any terminating new line character, as a separate field. For example, if your input CSV file contains:</p>

<pre>
1,2,3,4
</pre>

<p>Your output file would be written like this:</p>

<pre>
1,",",2,",",3,",",4,"
"
</pre>

<p>You should change the <code>for</code> loop to this:</p>

<pre><code>for row in csv.reader(f1):
    # process the row
    wr.writerow(row)
</code></pre>

<p>Now the input CSV file will be parsed into fields and <code>row</code> will contain a list of strings - one for each field. For the previous example, <code>row</code> would be:</p>

<pre><code>for row in csv.reader(f1):
    print(row)
</code></pre>

<pre>
['1', '2', '3', '4']
</pre>

<p>And when that list is passed to the <code>csv.writer</code> the output to the file will be:</p>

<pre>
1,2,3,4
</pre>

<hr>

<p>Putting all of that together you get this code:</p>

<pre><code>import csv

with open('input_1.csv') as f1, open('out.csv', 'w', newline='') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    for row in csv.reader(f1):
        wr.writerow(row)
</code></pre>

python csv