-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
  • 477
  • 2
  • 10
  • 24

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
  • 52,989
  • 9
  • 71
  • 124
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
  • 3,033
  • 1
  • 23
  • 28
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,993
  • 3
  • 26
  • 49