Skip to content
Advertisement

Exporting a PostgreSQL query to a csv file using Python

I need to export some rows from a table in a PostgreSQL database to a .csv file using a Python script:

JavaScript

But when I run the script I get this:

JavaScript

Does anyone know what can be wrong or give me a tip about?

Advertisement

Answer

The copy is not an SQL command, it is a command specific for the Postgres terminal client psql and cannot be used in this context.

Use copy_expert(sql, file, size=8192) instead, e.g.:

JavaScript

Read more about the function in the documentation.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement