【发布时间】:2016-12-29 23:19:02
【问题描述】:
如果我的表是 schema_one.table_five 并且我的文件名是 file_to_import.csv.gz,我应该为 copy_expert() cmd 提供什么参数以便将文件内容复制到表中?
这是我正在尝试的:
this_copy = '''COPY schema_one.table_five FROM STDIN with CSV'''
this_file = "file_to_import.csv.gz"
con = psycopg2.connect(dbname=dbname, host=host, port=port, user=user, password=password)
cur = con.cursor()
cur.copy_expert(this_copy, this_file)
这会产生错误:
cur.copy_expert(this_copy, this_file)
TypeError: file must be a readable file-like object for COPY FROM; a writable file-like object for COPY TO.
那么我如何告诉命令先解压缩文件,然后指定一个分隔符(在本例中为'|')以便处理它。
第二个问题。如果我的文件位于名为“files_to_import”的目录中,即/home/dir1/dir2/files_to_import/file_to_import.csv.gz,有没有一种方法可以只指定目录并在该目录中的所有文件中复制 pgm (到同一张桌子)?它们都是 .csv.gz 文件。
已添加 12-30-16 0940 MST -- 回复评论: 试图让 COPY 语句正确,但所有这些错误 ---
this_file = "staging.tbl_testcopy.csv.gz"
this_copy_01 = '''COPY staging.tbl_testcopy_tmp FROM STDIN'''
this_copy_02 = '''COPY staging.tbl_testcopy_tmp FROM %s'''
this_copy_03 = '''COPY staging.tbl_testcopy_tmp FROM (%s)'''
this_copy_04 = '''COPY staging.tbl_testcopy_tmp FROM f'''
with gzip.open(this_file, 'rb') as f:
try:
cur.copy_expert(this_copy_01, f)
except Exception, e:
print e
try:
cur.copy_expert(this_copy_02, f)
except Exception, e:
print e
try:
cur.copy_expert(this_copy_03, f)
except Exception, e:
print e
try:
cur.copy_expert(this_copy_04, f)
except Exception, e:
print e
所有这些错误,在同一个地方。那么在“FROM”之后应该是什么?
syntax error at or near "STDIN"
LINE 1: COPY staging.tbl_testcopy_tmp FROM STDIN
^
syntax error at or near "%"
LINE 1: COPY staging.tbl_testcopy_tmp FROM %s
^
syntax error at or near "("
LINE 1: COPY staging.tbl_testcopy_tmp FROM (%s)
^
syntax error at or near "f"
LINE 1: COPY staging.tbl_testcopy_tmp FROM f
^
【问题讨论】: