I am using the copy_expert
method in psycopg2
to copy data from a CSV file to a postgresql table. I have postgres table like this:
create table my_table (
cola text,
colb text,
colc text,
cold text,
cole text,
colf text,
colg text
)
And a CSV containing data like for the first five columns like this:
cola,colb,colc,cold,cole
1,foo,a,10,vvv
2,bar,b,20,www
3,baz,c,30,xxx
4,boo,d,40,yyy
5,baa,e,50,zzz
I would like to copy the CSV data for the first five columns, while also specifying values for colf
and colg
(each row should have the same value for colf
and colg
).
I can copy the first five columns to my table like this:
conn = psycopg2.connect('dbname=name user=username')
cur = conn.cursor()
copy_sql = """
copy my_table (cola, colb, colc, cold, cole)
from stdin with
csv
header
delimiter as ','
"""
from_csv = '/path/to/data.csv'
with open(from_csv, 'r') as f:
cur.copy_expert(sql=copy_sql, file=f)
conn.commit()
cur.close()
How can I also specify values for the last two columns using python? I know that I can specify default values in the table DDL, like this:
create table my_table (
cola text,
colb text,
colc text,
cold text,
cole text,
colf text default 'foo',
colg text default 'bar'
)
But I'd like to add the values using python, since each CSV upload will have its own values for colf
and colg
, and these values are determined by logic in my python code.