'Why is there an empty line after every record when writing a CSV file?

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



Solution 1:[1]

If there is an empty line every second line, you need to add newline='' like so:

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

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2 John Giorgio