Home > Enterprise >  Why is there an empty line after every record when writing a CSV file?
Why is there an empty line after every record when writing a CSV file?

Time:02-12

I have some lists and want to write them in a CSV file. Every list has 9200 items.

And every list must be a column in a CSV file.

I write this code:

file_path = os.path.join(os.path.realpath(folder_name), 'file_wanted.csv')
file_list = [list_1, list_2, list_3, list_4, list_5, list_6, list_7, list_8]
exported = zip_longest(*file_list)

with open(file_path, "w ", errors="ignore") as file:
    write = csv.writer(file)
    write.writerow(["list_1", "list_2", "list_3", "list_4", "list_5", "list_6", "list_7", "list_8"])
    write.writerows(exported)

But I have the file like that

Csv file I have

Is there a better way to write the code so that the extra line doesn't bloom for me after every record

CodePudding user response:

So there is an empty line every second line?

u need to add newline='' like so:

with open(file_path,"w ",errors="ignore", newline='') as file:

CodePudding user response:

Pandas is your friend.

import numpy as np, pandas as pd, os
from itertools import zip_longest

file_path = os.path.join(os.path.realpath(folder_name))
exported = list(zip_longest(list_1, list_2, list_3, list_4, 
                            list_5, list_6, list_7, list_8, fillvalue=np.nan))

df = pd.DataFrame(exported)
df.to_csv(file_path, index=False)
  • Related