Home > Blockchain >  Why do I have empty rows when I create a CSV file?
Why do I have empty rows when I create a CSV file?

Time:12-06

Im trying to create a new csv file which evaluates data about a construction site operation from an ASCII table in CSV format file. I have figured out how to create a CSV file, but I always get a blank line between the lines. Why is that?

import csv

header = ['name', 'area', 'country_code2', 'country_code3']
data = ['Afghanistan', 652090, 'AF', 'AFG']

file_object = open("new_file.csv", "w")
writer = csv.writer(file_object, delimiter=";")
writer.writerow(header)
writer.writerow(data)
file_object.close()

that how my csv file looks like:

name   area   country_code2   country_code3

Afghanistan   652090   AF   AFG

CodePudding user response:

Specify newline='' to eliminate the extra new line.

If newline='' is not specified on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling. [1]

with open('new_file.csv', 'w', newline='') as file_object:
    writer = csv.writer(file_object, delimiter=";")
    writer.writerow(header)
    writer.writerow(data)
  • Related