Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python skips line when printing to CSV

Tags:

python

csv

I am trying to create .csv file.

For some reason it skips line before printing entry.

Here is the output

enter image description here

But here is what I need

enter image description here

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)
like image 773
Rhonda Avatar asked Oct 11 '25 23:10

Rhonda


1 Answers

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:

  • portable way to write csv file in python 2 or python 3
  • csv writer expected byte like and space between rows

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

like image 131
Jean-François Fabre Avatar answered Oct 15 '25 02:10

Jean-François Fabre