Oct-02-2016, 05:58 AM
I'm a Newby,
I tried to insert columnar data sets in several CSV files into PostgreSQL database.
I tried this using copy_expert(sql, file) in psycopg2 as explained in this website .
However i got an error stating;
I tried to insert columnar data sets in several CSV files into PostgreSQL database.
I tried this using copy_expert(sql, file) in psycopg2 as explained in this website .
However i got an error stating;
E:\directory\path\Report1.csv Traceback (most recent call last): File "E:\Shared Folder Home\Python\Python3\postgreSQLDBConnect2.py", line 33, in <module> process_csv(connection, site, f) File "E:\Shared Folder Home\Python\Python3\postgreSQLDBConnect2.py", line 22, in process_csv cursor.copy_expert(sql=SQL_STATEMENT % table_name, file=file_object) TypeError: file must be a readable file-like object for COPY FROM; a writable file-like object for COPY TO.python code i used is as follows;
#!/usr/bin/python3.5 # -*- coding: utf8 -*- import os, glob, psycopg2, shutil, sys path = 'E:\\directory\\path\\' arc_path = 'E:\\directory\\arc\path\\' site = 'a location' db_conn = "dbname='testdb' user='postgres' host='localhost' password='password'" connection = psycopg2.connect(db_conn) SQL_STATEMENT = """ COPY %s FROM STDIN WITH CSV HEADER DELIMITER AS ',' """ def process_csv(conn, table_name, file_object): cursor = conn.cursor() cursor.copy_expert(sql=SQL_STATEMENT % table_name, file=file_object) conn.commit() cursor.close() if not os.path.exists(arc_path): os.makedirs(arc_path) file_list = glob.glob(path + "*.csv") for f in file_list: print(f) process_csv(connection, site, f) shutil.move(f, arc_path) connection.close()Can some help to solve this error? Thank you very much for your time & effort.