Python and writing a CSV file

Skip Montanaro skip at pobox.com
Sun Jan 25 19:05:23 CET 2004


    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





More information about the Python-list mailing list