I have created various lists and would like to write them to a csv file. That means there is List A List B List C List D - and so on
I tried to summarize the lists as follows
adress_label = [Anrede.anrede[0], Titel.titel[0], Name.vorname[0], Name.nachname[0], Adress_zus.adress_zus[0],
Strasse.strasse[0], str(PLZ.plz[0]), Stadt.stadt[0]]
with open('adress_list.csv', 'w') as adress_list:
adress_writer = csv.writer(adress_list, delimiter=',', quotechar="'", quoting=csv.QUOTE_MINIMAL)
adress_writer.writerow(adress_label)
However, the result is not written correctly to the csv file. The results of the various lists are written in 1 column instead of 1 column per list element.
Unfortunately I have not found an answer to my question here in the forum. How can I add different list elements to a csv file in Python?
I have created an example to help you understand better how it works.Using writer.writerow
you print data to csv per column, using writer.writerows
you print data per row.Also, zip
is an iterator of multiple lists.
import numpy as np
import csv
listA = [ {"name":"Text1","age":30},{"name":"Text4","age":20} ]
listB = [ {"name":"Text2","age":40},{"name":"Text5","age":35} ]
listC = [ {"name":"Text3","age":50},{"name":"Text6","age":70} ]
with open('address_list.csv', 'w', newline='') as file:
writer = csv.writer(file)
for (a,b,c) in zip(listA,listB,listC):
writer.writerow([a['name']])