Is anyone happy with csv module?

massimo s. devicerandom at gmail.com
Tue Dec 11 16:31:11 EST 2007


On 11 Dic, 20:24, "Guilherme Polo" <ggp... at gmail.com> wrote:

>
> Post your actual problem so you can get more accurate help.

Hi Guilhermo,
I have not an actual problem. I'm just trying to use the CSV module
and I mostly can get it working. I just think its interface is much
less than perfect. I'd like something I can, say, give a whole
dictionary in input and obtain a CSV file in output, with each key of
the dictionary being a column in the CSV file. Or a row, if I prefer.
Something like:

dict={'First':[1,2,3,4],'Second':[10,20,30,40],'Third':
[100,200,300,400]}
f=open('test.csv','w')
try:
    csv_write_dict(f,dict,keys='columns',delimiter=',')
finally:
    f.close()

and obtaining:
First,Second,Third
1,10,100
2,20,200
3,30,300
4,40,400

Doing the same thing with the current csv module is much more
cumbersome: see this example from http://www.oreillynet.com/onlamp/blog/2007/08/pymotw_csv.html

f = open(sys.argv[1], 'wt')
try:
    fieldnames = ('Title 1', 'Title 2', 'Title 3')
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    headers = {}
    for n in fieldnames:
        headers[n] = n
    writer.writerow(headers)
    for i in range(10):
        writer.writerow({ 'Title 1':i+1,
                          'Title 2':chr(ord('a') + i),
                          'Title 3':'08/%02d/07' % (i+1),
                          })
finally:
    f.close()


Another unrelated quirk I've found is that iterating the rows read by
a csv reader object seems to erase the rows themselves; I have to copy
them in another list to use them.

Probably it's me not being a professional programmer, so I don't
understand that somehow the csv module *has* to be done this way. If
it's so, I'd like to know about it so I can learn something.

> For the questions you placed: google for them, look at python pep 305

I googled (before and after sending this post). I found mentions of
people writing a purely Python csv module but I didn't find their
code. As for pep 305, thanks, but it seems just to be a description of
the actual csv module (useful,anyway).

m.



More information about the Python-list mailing list