Python and writing a CSV file

engsol engsolnorm at ipns.com
Sun Jan 25 14:38:50 EST 2004


On Sun, 25 Jan 2004 12:05:23 -0600, Skip Montanaro <skip at pobox.com>
wrote:

>
>    Kevin> Thanks for responding. Currently we do not have Python 2.3
>    Kevin> installed on our server, is there another way to perform this
>    Kevin> task with another module or without a module? Thanks!
>
>The Object Craft module does write CSV files.  When we wrote the module
>included with 2.3, we conciously tried to keep it compatible with 2.2, so
>you might well be able to just download it and compile it with 2.2 like any
>other third-party module.  If that fails, let me know and I'll see if I
>can't steer you in the right direction.
>
>Failing all that, if your data is very well-behaved, you can write valid CSV
>data quite easily.  Given a list of lists like so:
>
>    data = [
>        [1, 2, 4, "My data"],
>        ["abc", "def", "ghi"],
>        ["234234234", 1.2e7, "!@##%^*"],
>    ]
>
>you should be able to write it to sys.stdout with something like (untested):
>
>    for row in data:
>        row = [str(e) for e in row]
>        print '"' + '","'.join(row) + '"'
>
>Note that the data above doesn't include quotation marks in any of the
>fields, the separator is always a comma, and all output will be fully
>quoted.  Also, it assumes you're on Windows where you'll automatically get
>CRLF terminators.
>
>You should be able to fairly easily extend the above code to handle those
>situations.
>
>Skip
>
Great timing!

I was about to post a question regarding CSV files.

I bread-boarded a small test script to learn how the csv thing works,
and it seems to work well.

The script is:

import csv

writer = csv.writer(file('csv_test.CSV', 'w'))

list_1 = ['a','b','c']
list_2 = ['d','e','f']
list_3 = list_1 + list_2

for ix in range(3):
    print list_3
    writer.writerow(list_3)

stdout reports:

['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f']

but the csv file shows:

a,b,c,d,e,f

a,b,c,d,e,f

a,b,c,d,e,f

So the question is, where does the extra crlf in the csv file come
from? And how do I get rid of it?

Thanks,
Norm



More information about the Python-list mailing list