使用 python 和 psycopg2 将 CSV 导入 postgres 时出错

Error when importing CSV to postgres with python and psycopg2

我尝试使用 python 和 psycopg2 将 CSV 文件从文件夹复制到 postgres table,但出现以下错误:

 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 psycopg2.ProgrammingError: must be superuser to COPY to or from a file
HINT:  Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.

我也尝试 运行 它通过 python 环境作为:

  constr = "dbname='db_name' user='user' host='localhost' password='pass'"
  conn = psycopg2.connect(constr)
  cur = conn.cursor()
  sqlstr = "COPY test_2 FROM '/tmp/tmpJopiUG/downloaded_xls.csv' DELIMITER ',' CSV;"
  cur.execute(sqlstr)

我仍然得到上面的错误。我试过 \copy 命令,但这只适用于 psql。为了能够通过我的 python 脚本执行此操作,有什么替代方法?

已编辑

在查看了@Ilja Everilä 提供的 link 之后,我尝试了这个:

cur.copy_from('/tmp/tmpJopiUG/downloaded_xls.csv', 'test_copy')

我收到一个错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument 1 must have both .read() and .readline() methods

这些方法怎么给?

尝试使用 cursor.copy_expert():

constr = "dbname='db_name' user='user' host='localhost' password='pass'"
conn = psycopg2.connect(constr)
cur = conn.cursor()
sqlstr = "COPY test_2 FROM STDIN DELIMITER ',' CSV"
with open('/tmp/tmpJopiUG/downloaded_xls.csv') as f:
    cur.copy_expert(sqlstr, f)
conn.commit()

您必须在 python 中打开文件 并将其传递给 psycopg,后者随后将其转发给 postgres 的标准输入。由于您使用 CSV 参数 COPY,因此您必须使用自己传递 COPY 语句的专家版本。

您也可以使用copy_from。见下方代码

with open('/tmp/tmpJopiUG/downloaded_xls.csv') as f:
 cur.copy_from(f, table_name,sep=',')
conn.commit()