Skip to main content
 首页 » 编程设计

python之psycopg2 copy_expert()之如何复制 gzip 压缩的 csv 文件

2025年02月15日15lovecherry

如果我的表是 schema_one.table_five 并且我的文件名为 file_to_import.csv.gz,我应该给 copy_expert() 命令什么参数才能将文件内容复制到表中?

这是我正在尝试的:

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 (同 table )?它们都是 .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 
                                           ^ 

请您参考如下方法:

copy_expert 的file 参数应该是一个类似对象的文件,而不是文件名。对于常规的 csv 文件,您可以使用:

with open("file_to_import.csv",  'rb') as this_file: 
    cur.copy_expert(this_copy, this_file) 

对于 gzip 文件,您可以使用 gzip 模块打开文件:

import gzip 
with gzip.open("file_to_import.csv.gz",  'rb') as this_file: 
    cur.copy_expert(this_copy, this_file) 

要更改分隔符,您必须更改 COPY 语句。查看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='|') 

没有自动导入目录中所有文件的命令,您必须获取目录内容的列表并循环遍历它。