-2

With the structure:

mylist = [ [a,b,c,d], [e,f,g,h], .......[w,x,y,z]]

How can I export to a .csv file using each column and row like? Is there useful functions to quickly format lists to .csv files this way? I want each value in list to be a new tab in excel.

a   b   c   d
e   f   g   h
............
w   x   y   z
cc6g11
  • 429
  • 1
  • 6
  • 22

3 Answers3

1

You could use :

sep = "\t"

mylist = [['a', 'b', 'c'], ['d', 'e', 'f']]

with open('my.csv', 'w') as csv:
    for row in mylist:
        csv.write(sep.join(row))
        csv.write("\n")

Or the official csv lib.

my.csv is now :

a   b   c
d   e   f
Eric Duminil
  • 48,038
  • 8
  • 56
  • 100
1

I think this should do what you want.

csv_lines = []
for line in mylist:
    csv_lines.append(",".join(line))

f = open("mylist.csv", "w")
f.write("\n".join(csv_lines))
f.close()

The file mylist.csv should then be read correctly by excel automatically.

Tim B
  • 2,488
  • 1
  • 17
  • 24
1

This is an efficient way of doing it if you list is not VERY huge

with open('filename.csv', 'w') as file_handle:
    file_handle.write(map(lambda x:x.join(", "), mylist).join("\n"))
Ajay Brahmakshatriya
  • 8,213
  • 3
  • 19
  • 41