I'm trying to save in a local .csv the results of query performed in python towards a PostgreSQL database (using psycopg2).
I'm able to print the result of the query in the console, but fail to export it to a csv file.
I've tried using the copy_to function, but even with the documentation I can't figure it out:
# Retrieve the records from the database with query
cursor.execute("SELECT col1 FROM myDB.myTable WHERE col1 > 2")
records = cursor.fetchall()
# Save to csv with copy_to
io = open('copy_to.csv', 'w')
cursor.copy_to(io, 'records', ',')
print("Copied records from query into file object using sep = ,")
io.close()
This provokes the error "psycopg2.ProgrammingError: relation "records" does not exist".
Is there a better way to store the query's result in a local table which could be passed in copy_to? Thanks for any tips!
copy_tois really meant to work on entire tables, not queries. Consider using python's csv library or pandas to write the csv file.