I am trying out the program for writing to a CSV file.
Here’s my code:
JavaScript
x
22
22
1
import csv
2
#field names
3
fields = ['Name','Branch','Year']
4
# data rows of CSV file
5
rows = [['Stef', 'Multimedia Technology','2'],
6
['Kani', 'Information Technology', '2'],
7
['Plazaa', 'Electronics Engineering', '4'],
8
['Lizzy', 'Computer Science', '4'],
9
['Reshmi', 'Multimedia Technology', '3'],
10
['Geetha','Electrical Engineering', '4'],
11
['Keerti', 'Aeronautical Engineering', '3']]
12
13
#writing to csv file
14
#writing to csv file
15
with open('records.csv','w') as csvfile:
16
#creating a csv writer object
17
csvwriter = csv.writer(csvfile)
18
#writing the fields
19
csvwriter.writerow(fields)
20
# writing the data rows
21
csvwriter.writerows(rows)
22
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.
JavaScript
1
8
1
with open('records.csv','w', newline='') as csvfile:
2
#creating a csv writer object
3
csvwriter = csv.writer(csvfile)
4
#writing the fields
5
csvwriter.writerow(fields)
6
# writing the data rows
7
csvwriter.writerows(rows)
8