Search code examples
pythonexcelcsvexport-to-csv

Why is there implemented a default blank row when writing csv from python linked list?


I have an example of writing a csv from a python linked list:

import csv

# field names 
fields = ['Name', 'Branch', 'Year', 'CGPA'] 

# data rows of csv file 
rows = [ ['Nikhil', 'COE', '2', '9.0'], 
     ['Sanchit', 'COE', '2', '9.1'], 
     ['Aditya', 'IT', '2', '9.3'], 
     ['Sagar', 'SE', '1', '9.5'], 
     ['Prateek', 'MCE', '3', '7.8'], 
     ['Sahil', 'EP', '2', '9.1']] 

with open('Test.csv', 'w') as f:
 
# using csv.writer method from CSV package
 
    write = csv.writer(f)
    write.writerow(fields)
    write.writerows(rows)

This works fine, except I have the following result:

Name,Branch,Year,CGPA

Nikhil,COE,2,9.0

Sanchit,COE,2,9.1

Aditya,IT,2,9.3

Sagar,SE,1,9.5

Prateek,MCE,3,7.8

Sahil,EP,2,9.1

As you can see, in my output csv file I have blank lines between the data. I don't understand where these unwanted line breaks come from.

Why is there an extra row on default? What is its purpose since it's not there in the input data?


Solution

  • You can add newline = '' in your writer part:

    import csv
    
    fields = ['Name', 'Branch', 'Year', 'CGPA']
    rows = [['Nikhil', 'COE', '2', '9.0'],
            ['Sanchit', 'COE', '2', '9.1'],
            ['Aditya', 'IT', '2', '9.3'],
            ['Sagar', 'SE', '1', '9.5'],
            ['Prateek', 'MCE', '3', '7.8'],
            ['Sahil', 'EP', '2', '9.1']]
    
    with open('Test.csv', 'w', newline = '') as f:
        writer = csv.writer(f)
        writer.writerow(fields)
        writer.writerows(rows)