简体   繁体   中英

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM