Home > Net >  Python syntax error - backslash in psql queries with psycopg2
Python syntax error - backslash in psql queries with psycopg2

Time:12-31

I have a small python script. I want to execute a psql command with the librairy psycopg2:

query = "\COPY ( select * from 'schema'.structure) TO 'path' DELIMITER ',' CSV HEADER;"

But I have a syntaxe error with the \COPY. I have tried to change it with '' and \\ but nothing seems to work. I don't want to use cur.copy_from.

Any suggestion ?

CodePudding user response:

If you want to use psycopg2 for COPYing with custom SQL, you have to use copy_expert. Assuming your query works, this way:

with open(file_path, "w") as outfile:
    cur.copy_expert("COPY (select * from 'schema'.structure) TO STDOUT DELIMITER ',' CSV HEADER", outfile)

You have to give a writeable file as second parameter and use TO STDOUT inside your query.

  • Related