Skip to content
Advertisement

Writing To CSV file Without Line Space in Python 3

I am trying out the program for writing to a CSV file.

Here’s my code:

import csv
#field names
fields = ['Name','Branch','Year']
# data rows of CSV file
rows = [['Stef', 'Multimedia Technology','2'],
    ['Kani', 'Information Technology', '2'],
    ['Plazaa', 'Electronics Engineering', '4'],
     ['Lizzy', 'Computer Science', '4'],
     ['Reshmi', 'Multimedia Technology', '3'],
     ['Geetha','Electrical Engineering', '4'],
     ['Keerti', 'Aeronautical Engineering', '3']]

#writing to csv file
#writing to csv file
with open('records.csv','w') as csvfile:
    #creating  a csv writer object
    csvwriter = csv.writer(csvfile)
    #writing the fields
    csvwriter.writerow(fields)
    # writing the data rows
    csvwriter.writerows(rows)

The program runs well. But in the CSV file, there is a blank newline space (without any entries) between each entry. How to eliminate that line in the resultant CSV file?

Advertisement

Answer

Recommended implementation per Python3 Documentation.

with open('records.csv','w', newline='') as csvfile:
    #creating  a csv writer object
    csvwriter = csv.writer(csvfile)
    #writing the fields
    csvwriter.writerow(fields)
    # writing the data rows
    csvwriter.writerows(rows)

https://docs.python.org/3/library/csv.html#csv.writer

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement