Csv output column by column (python)

Question:

How to write the lists that have lists in a csv file on different columns, so that you can write the names of the columns (headers) at the beginning. And then my code writes everything in one column line by line. Here is the code:

import csv
from mypars import all_id_z
from mypars import all_href_z

id_z = all_id_z
href_z = all_href_z

with open('zakup.csv', 'w', newline='') as csv_file:
    csv_writer = csv.writer(csv_file)
    for item in id_z:
        csv_writer.writerow([item])
    for item in href_z:
        csv_writer.writerow([item])

Thanks for the answers!

Answer:

If the length of the lists is the same, then you can use the Pandas module:

import pandas as pd

lst1 = [1,2,3,4,5]
lst2 = [3,5,8,9,1]
lst3 = [3,-11,0,2,7]

data = dict(col1=lst1, col2=lst2, col3=lst3)

df = pd.DataFrame(data)

df.to_csv(r'c:/temp/res.csv', sep=';', index=False)

result:

from pathlib import Path

print(Path(r'c:/temp/res.csv').read_text())

col1;col2;col3
1;3;3
2;5;-11
3;8;0
4;9;2
5;1;7
Scroll to Top