Export Postgre SQL table to text (csv) via psycopg2

Asked

Viewed 179 times

0

I am trying to export a table from the Postgres database to a txt (csv) file via Python, via psycopg2. However, I am encountering an error. The code is as follows (I switched login information to post):

import psycopg2

# Definição da conexão com a DB onde informo o nome, o usuário, a senha e o IP.
conn = psycopg2.connect("dbname=dbname user=user password=password host=iphost")

# Abertura da conexão para execução de queryes.
cur = conn.cursor()

# Query de consulta da tabela empresa. columns=None

f = open("\\\\server\\arquivos\\BD\\log.txt", "w")
copy_to(f, 'wphd.empresa', sep=';', null='')
f.close()

# Fechar conexão com a DB.
cur.close()
conn.close()

The error that returns is as follows:

Traceback (most recent call last):
  File "C:\Py\Db\Conn_B_working.py", line 12, in <module>
    copy_to(f, 'wphd.empresa', sep=';', null='')
NameError: name 'copy_to' is not defined

Can anyone tell me what’s missing? Grateful!

1 answer

0


As you can see in documentation, copy_to is a class method cursor:

cur.copy_to(f, 'wphd.empresa', sep=';', null='')
  • Fast and accurate. Thank you very much and sorry for the shame of beginner. It worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.