joseph
joseph

Reputation: 11

Exporting list of arrays in python as csv

I have a list of array in python that I'd like to export to a csv file, I am able to export a csv but am having some trouble with the line breaks. My list looks like this:

myList = [[itema, itemb], [itema_1,itemb_1], ... , [itema_n, itemb_n]]

I would like for my csv file to be like this:

itema, item
itema_1, item_1
...
itema_n, item_n

this is my current code, which gives me ([itema, itemb],[itema_1,itemb_1], etc.)

with open('sng_pyout', 'wb') as output:
    new_writer = csv.writer(output)
    new_writer.writerow(myList)

Upvotes: 1

Views: 511

Answers (3)

janos
janos

Reputation: 124774

Use the writerows (plural!) method to write all your rows at once:

with open('sng_pyout', 'wb') as output:
    new_writer = csv.writer(output)
    new_writer.writerows(myList)

The writerow (singular) takes a list of columns. And since your myList is a list, it assumed it's a list of columns, so it quoted its elements and wrote as csv:

"['jack', ' 4']","['mike', ' 12']"

The writerows (plural!) method expects a list of list of columns, and that's perfect for your myList.

Upvotes: 1

Joan Smith
Joan Smith

Reputation: 931

Looks like you're just telling the csv.writer to write a single row, since each call to csv.writerow will write one row with everything you pass into it. Instead:

with open('sng_pyout', 'wb') as output:
    new_writer = csv.writer(output)
    for sub_list in myList:
        new_writer.writerow(sub_list)

Upvotes: 1

bigblind
bigblind

Reputation: 12877

Try it as follows:

with open('sng_pyout', 'wb') as output:
    new_writer = csv.writer(output)
    for row in myList:
        new_writer.writerow(row)

Upvotes: 0

Related Questions