Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Python lists to columns in csv

Tags:

python

list

csv

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?

like image 594
Alex Chumbley Avatar asked Jul 17 '13 15:07

Alex Chumbley


People also ask

How do I write a list of elements in a CSV file in Python?

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.

How do I make a list into a CSV file?

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.

What method takes a list argument and writes it to a CSV file?

writerows() This function takes a list of iterables as parameter and writes each item as a comma separated line of items in the file.


2 Answers

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) 
like image 68
Joran Beasley Avatar answered Sep 27 '22 20:09

Joran Beasley


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

enter image description here

like image 20
Ashok Kumar Jayaraman Avatar answered Sep 27 '22 21:09

Ashok Kumar Jayaraman