Psycopg2 | collapse row to string

skip at pobox.com skip at pobox.com
Tue Nov 21 16:19:15 EST 2006


    Jeff> Is there an easy want to create a delimited string from this, for
    Jeff> example:

    Jeff> for row in rows:
    Jeff>     if checksomething == 100:
    Jeff>         newline = row[].combine("delimiter of some kind")
    Jeff>         resultfile.write(newline)

By "delimited string" do you mean something that can handle fields in which
your delimiter appears?  If so, you should look at the csv.writer class.  If
you're absolutely certain your delimiter won't occur in your output, you can
just stringify the values and join them:

    delimiter = ","
    for row in rows:
        if checksomething == 100:
            resultfile.write(delimiter.join([str(elt) for elt in row]))

If you know all your row values are already strings it's even easier:

    delimiter = ","
    for row in rows:
        if checksomething == 100:
            resultfile.write(delimiter.join(row))

Skip



More information about the Python-list mailing list