There is always a blank line when writing data using the csv module in python

When we use the csv module to write data to the csv file, whether it is using the writerow() method or writerows(), each row of data in the csv file is always separated by a blank line

import csv
data = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
with open('data.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(['row1','row2','row3','row4'])
    writer.writerows(data)

The data in the csv file looks like this:

The solution is

with open('data.csv', 'w',newline = '') as f:

Add the keyword parameter newline ='' in the open method

import csv
data = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
with open('data.csv', 'w',newline = '') as f:
    writer = csv.writer(f)
    writer.writerow(['row1','row2','row3','row4'])
    writer.writerows(data)

The result is:

Guess you like

Origin blog.csdn.net/Thanours/article/details/83515640