【发布时间】:2016-10-06 01:20:06
【问题描述】:
我尝试使用 python 和 psycopg2 将 CSV 文件从文件夹复制到 postgres 表,但出现以下错误:
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ä 提供的链接后,我尝试了这个:
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
我如何给出这些方法?
【问题讨论】:
-
看看initd.org/psycopg/docs/cursor.html#cursor.copy_from 或initd.org/psycopg/docs/cursor.html#cursor.copy_expert,它们似乎使用了标准输入和标准输出,这将允许普通数据库用户运行它。
-
谢谢。请参阅编辑。
标签: python postgresql csv psycopg2