我正在尝试使用psycopg2创建多个(4000)csv文件到我的postgres数据库中。所有csv文件都具有相同的列名称和类型。我只是无法弄清楚如何有效地订购这个。
Python 3.5,Postgre - 9.5.12
问题:
我能不能再简化这个过程了
import psycopg2
import os
conn = psycopg2.connect("dbname=postgres user=postgres")
cur = conn.curser()
# file_dir == directory containing all the .csv
sec_files = os.listdir("file_dir")
for files in sec_files:
# Cuts off all whitespace and .csv
sec_name = ''.join(files.split())[:-4]
cur.execute(''' CREATE TABLE '%s' (
Date NOT NULL UNIQUE DATE PRIMARY KEY
col2 FLOAT NOT NULL
col3 FLOAT NOT NULL
col4 FLOAT NOT NULL
col5 FLOAT NOT NULL
col6 FLOAT NOT NULL
col7 INTEGER NOT NULL )''').format(sec_name)
print("Table created ",sec_name)
with open(os.path.abspath(files),'r') as f:
next(f)
for row in reader:
cur.copy_from(f,sec_name, sep=',')
conn.commit()
print('Data inserted into ', sec_name, ' completed')
答案 0 :(得分:0)
重新格式化你的代码,没有改变你插入数据的方式,因为那样会更加重构但是根据你所展示的,这将是执行你所呈现的代码的正确方法。
import os
import psycopg2
from psycopg2.extensions import AsIs
query = """
CREATE TABLE %(table)s (
Date NOT NULL UNIQUE DATE PRIMARY KEY
col2 FLOAT NOT NULL
col3 FLOAT NOT NULL
col4 FLOAT NOT NULL
col5 FLOAT NOT NULL
col6 FLOAT NOT NULL
col7 INTEGER NOT NULL)
"""
sec_files = os.listdir('file_dir')
conn = psycopg2.connect('dbname=postgres user=postgres')
with conn.cursor() as cursor:
for file in sec_files:
name = os.path.basename(file).split('.')[0]
cursor.execute(query, {'table': AsIs(name)})
print('Table created', name)
with open(os.path.abspath(file), 'r') as fin:
next(f)
cursor.copy_from(f, name, sep=',')
print('Data inserted into ', name, ' complete')