4

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)
Rhonda
  • 1,661
  • 5
  • 31
  • 65

2 Answers2

6

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)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • the issue is specific to windows and is covered in the [documentation](https://docs.python.org/3/library/csv.html#id3) – Aaron Sep 05 '17 at 14:38
2

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Henry
  • 362
  • 2
  • 8