Tho*_*ers 5 python csv gzip psycopg2
如果我的表是 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)
Run Code Online (Sandbox Code Playgroud)
这会产生一个错误:
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.
Run Code Online (Sandbox Code Playgroud)
那么我如何告诉命令首先解压缩文件,然后指定一个分隔符(在本例中为“|”),以便可以对其进行处理。
次要问题。如果我的文件位于名为“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
Run Code Online (Sandbox Code Playgroud)
所有这些错误,都在同一个地方。那么'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
^
Run Code Online (Sandbox Code Playgroud)
file
的参数应该copy_expert
是一个类似文件的对象,而不是文件名。对于常规 csv 文件,您可以使用:
with open("file_to_import.csv", 'rb') as this_file:
cur.copy_expert(this_copy, this_file)
Run Code Online (Sandbox Code Playgroud)
对于 gzip 压缩文件,您可以使用该gzip
模块打开该文件:
import gzip
with gzip.open("file_to_import.csv.gz", 'rb') as this_file:
cur.copy_expert(this_copy, this_file)
Run Code Online (Sandbox Code Playgroud)
要更改分隔符,您必须更改 COPY 语句。有关更多信息,请参阅复制文档。它可能更容易使用copy_from
(有一个可选sep
参数)而不是copy_expert
.
with gzip.open("file_to_import.csv.gz", 'rb') as this_file:
cur.copy_from(this_file, 'staging.tbl_testcopy_tmp', sep='|')
Run Code Online (Sandbox Code Playgroud)
没有命令可以自动导入目录中的所有文件,您必须获取目录内容的列表并循环遍历它。