0

I am trying to add extra columns in a csv file after processing an input csv file. But, I am getting extra new line added after each line in the output.

What's missing or wrong in my below code -

import csv
with open('test.csv', 'r') as infile:
     with open('test_out.csv', 'w') as outfile:
         reader = csv.reader(infile, delimiter=',')
         writer = csv.writer(outfile, delimiter=',')
         for row in reader:
                colad = row[5].rstrip('0123456789./ ')
                if colad == row[5]:
                    col2ad = row[11]
                else:
                    col2ad = row[5].split(' ')[-1]
                writer.writerow([row[0],colad,col2ad] +row[1:])

I am processing huge a csv file so would like to get rid of those extra lines.

yatri
  • 33
  • 6

1 Answers1

1

I had the same problem on Windows (your OS as well, I presume?). CSV and Windows as combination make a \r\r\n at the end of each line (so: double newline).

You need to open the output file in binary mode:

with open('test_out.csv', 'wb') as outfile:

For other answers:

Python's CSV writer produces wrong line terminator

CSV in Python adding an extra carriage return

Community
  • 1
  • 1
Nander Speerstra
  • 1,377
  • 6
  • 23
  • 26