How to generate a csv file from a list?

2

Hello, I have the following list

  l=[[1,2,3,4],[5,6,7,8]]

and I want to generate a csv file something like this:

1 5
2 6
3 7
4 8

the code that I have worked on is this

with open("output.csv", "wb") as f:
  writer = csv.writer(f)
  writer.writerows(l)

but what it does is generate a csv file like this:

1,2,3,4

5,6,7,8

and what I really want is that each sublist is a column of the csv file I have already looked at several examples but none clarifies the doubt. I hope you can help me.

    
asked by Yeison Ordoñez 02.06.2016 в 17:40
source

2 answers

2

The best thing is that you use NumPy to be able to transpose the data comfortably and then write them in a CSV:

import numpy as np

l=[[1,2,3,4],[5,6,7,8]]
datos = np.asarray(l)
np.savetxt("output.csv",   # Archivo de salida
           datos.T,        # Trasponemos los datos
           fmt="%d",       # Usamos números enteros
           delimiter=",")  # Para que sea un CSV de verdad
    
answered by 02.06.2016 / 17:50
source
3

What you need is to interlace the sublists before sending them to the CSV file. It is done with the function zip and passing the list:

with open("output.csv", "wb") as f:
  writer = csv.writer(f)
  writer.writerows(zip(*l))

In python2 the function zip create a new list in memory, not as in python3 that create an iterator. If you are going to save a lot of data, it is more efficient than user itertools.izip :

import itertools

with open("output.csv", "wb") as f:
      writer = csv.writer(f)
      writer.writerows(itertools.izip(*l))
    
answered by 02.06.2016 в 17:53