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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With