私のテーブルがschema_one.table_fiveで、ファイル名がfile_to_import.csv.gzの場合、ファイルの内容をテーブルにコピーするためにcopy_expert()cmdをどのようにしますか?psycopg2 copy_expert() - gzip形式のcsvファイルをコピーするには?
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
^
はそれを試みたが、エラーを得た構文エラーで、または近くに "STDIN" LINE 1:COPY schema_one.table_five from STDIN WITH CSV HEADER' –
あなたは 'sys.stdin'を使用しています。これは私の答えではありません。ファイルハンドルを渡す必要があります。 – Alasdair
'f'に変更しましたが、これはファイルハンドルであり、まだエラーがあります。コードと結果については上記の編集OPをご覧ください。 FROMがエラーを引き起こした後に来るもの(または私が試したすべてのもの)のように見えます。 COPYステートメントの適切な構築に関する提案はありますか?私がやろうとしているのは、自分のファイルから自分のテーブルにCOPYすることだけです。また、私はcopy_expert()の代わりにcopy_from()を使用する必要がありますか?私はwのcopy_from()をちょっとばかにしたが、どこにもいなかった。 –