-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
5
  • 1
    Possible duplicate of Writing to CSV with Python adds blank lines Commented Mar 1, 2017 at 14:50
  • 1
    csv files don't have tabs. Commented Mar 1, 2017 at 14:51
  • 1
    Look at the builtin-in csv module's docs. And csv files don't have tabs. Commented Mar 1, 2017 at 14:52
  • They can have tabs. c in csv doesn't always mean comma. It sometimes means "character" Commented Mar 1, 2017 at 14:52
  • The documentation explains writing CSV, and gives you an example in code. Commented Mar 1, 2017 at 14:53

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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"))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.