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>open file without b mode</p>

<p>b mode open your file as binary</p>

<p>you can open file as w</p>

<pre><code>open_file = open("filename.csv", "w")
</code></pre>

python csv