suppose I have an numpy array with structure like this:
[['a','b','c'],[1,2,3],['i','j','k','l'],[5,10,15,20]]
and I want to save it to a csv file that looks like this
a, 1, i, 5
b, 2, j, 10
c, 3, k, 15
, , l, 20
the columns with shorter length just fill with blank. How can I do that?
The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class.
Too bad because CSV format doesn't do "nested".
Step 1: In order to read rows in Python, First, we need to load the CSV file in one object. So to load the csv file into an object use open() method. Step 2: Create a reader object by passing the above-created file object to the reader function. Step 3: Use for loop on reader object to get each row.
Use itertools.izip_longest
:
>>> from itertools import izip_longest
>>> lis = [['a','b','c'],[1,2,3],['i','j','k','l'],[5,10,15,20]]
>>> list(izip_longest(*lis, fillvalue=''))
[('a', 1, 'i', 5),
('b', 2, 'j', 10),
('c', 3, 'k', 15),
('', '', 'l', 20)]
Use csv.writerows(izip_longest(*lis, fillvalue=''))
to write this to a csv file.
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