简体   繁体   中英

Python skips line when printing to CSV

I am trying to create .csv file.

For some reason it skips line before printing entry.

Here is the output

在此处输入图片说明

But here is what I need

在此处输入图片说明

Below is code. Apparently if line != "": doesn't work

import csv

#-----------------------------------
def csv_writer(data,path):
    """
    Write data to a CSV file path
    """
    with open(path, "w") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            if line != "":
                writer.writerow(line)

#-----------------------------------
if __name__ == "__main__":
    data = ["first_name,last_name,city".split(","),
            "Tyrese,Hirthe,Strackeport".split(","),
            "Jules,Dicki,Lake Nickolasville".split(","),
            "Dedric,Medhurst,Stiedemannberg".split(",")
            ]
    path = "output.csv"
    csv_writer(data,path)

Some python versions (on windows) have an issue with that with open(path, "w") as csv_file: . A spurious carriage return char is inserted , creating a blank line after each line.

You have to add newline="" as stated in the documentation. Python 3:

with open(path, "w",newline="") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')

As for python 2:

with open(path, "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')

see also:

(note that latest Python versions on Windows don't need this anymore, but the documentation continues to state it)

When you open the file you need to pass the keyword argument newline with a blank string. This will prevent the newlines being added between rows. Your function should be:

def csv_writer(data,path):
"""
Write data to a CSV file path
"""
with open(path, "w", newline = '') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for line in data:
        if line != "":
            writer.writerow(line)

Note that this is only an issue on Windows.

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