I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:
with open('test.csv', 'wb') as f: writer = csv.writer(f) for val in test_list: writer.writerow([val])
If I add another for
loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?
csv is the name of the file, the “w” mode is used to write the file, to write the list to the CSV file write = csv. writer(f), to write each row of the list to csv file writer. writerow() is used.
The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class.
writerows() This function takes a list of iterables as parameter and writes each item as a comma separated line of items in the file.
Change them to rows:
rows = zip(list1, list2, list3, list4, list5)
Then just:
import csv with open(newfilePath, "w") as f: writer = csv.writer(f) for row in rows: writer.writerow(row)
The following code writes python lists into columns in csv
import csv from itertools import zip_longest list1 = ['a', 'b', 'c', 'd', 'e'] list2 = ['f', 'g', 'i', 'j'] d = [list1, list2] export_data = zip_longest(*d, fillvalue = '') with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile: wr = csv.writer(myfile) wr.writerow(("List1", "List2")) wr.writerows(export_data) myfile.close()
The output looks like this
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