user2883071
user2883071

Reputation: 980

Using Python's CSV library to print an array as a csv file

I have a python list as such:

[['a','b','c'],['d','e','f'],['g','h','i']]

I am trying to get it into a csv format so I can load it into excel:

a,b,c
d,e,f
g,h,i

Using this, I am trying to write the arary to a csv file:

with open('tables.csv','w') as f:
    f.write(each_table)

However, it prints out this:

[
[
'
a
'
,
...
...

So then I tried putting it into an array (again) and then printing it.

each_table_array=[each_table]
with open('tables.csv','w') as f:
        f.write(each_table_array)

Now when I open up the csv file, its a bunch of unknown characters, and when I load it into excel, I get a character for every cell.

Not too sure if it's me using the csv library wrong, or the array portion.

I just figured out that the table I am pulling data from has another table within one of its cells, this expands out and messes up the whole formatting

Upvotes: 1

Views: 838

Answers (2)

Kasravnd
Kasravnd

Reputation: 107357

As a more flexible and pythonic way use csv module for dealing with csv files Note that as you are in python 2 you need the method newline='' * in your open function . then you can use csv.writer to open you csv file for write:

import csv
with open('file_name.csv', 'w',newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerows(main_list)

From python wiki: If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

Upvotes: 2

Ying Xiong
Ying Xiong

Reputation: 4948

You need to use the csv library for your job:

import csv
each_table = [['a','b','c'],['d','e','f'],['g','h','i']]
with open('tables.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    for row in each_table:
        writer.writerow(row)

Upvotes: 3

Related Questions