Skip to content Skip to sidebar Skip to footer

How To Save Results Of Postgresql To Csv/excel File Using Psycopg2?

I use driving_distance in postgresql to find distances between all nodes, and here's my python script in pyscripter, import sys #set up psycopg2 environment import psycopg2 #driv

Solution 1:

Based on Psycopg2's cursor.copy_expert() and Postgres COPY documentation and your original code sample, please try this out. I tested a similar query export on my laptop, so I'm reasonably confident this should work, but let me know if there are any issues.

import sys

#set up psycopg2 environment
import psycopg2

#driving_distance module
#note the lack of trailing semi-colon in the query string, as per the Postgres documentation
query = """
    select *
    from driving_distance ($$
        select
            gid as id,
            start_id::int4 as source,
            end_id::int4 as target,
            shape_leng::double precision as cost
        from network
        $$, %s, %s, %s, %s
    )
"""

#make connection between python and postgresql
conn = psycopg2.connect("dbname = 'routing_template' user = 'postgres' host = 'localhost' password = 'xxxx'")
cur = conn.cursor()

outputquery = "COPY ({0}) TO STDOUT WITH CSV HEADER".format(query)

with open('resultsfile', 'w') as f:
    cur.copy_expert(outputquery, f)

conn.close()

Post a Comment for "How To Save Results Of Postgresql To Csv/excel File Using Psycopg2?"