I am taking data from a table (Postgres) and trying to append to an existing file. The requirement is to insert data to respective columns
I know only to append row-wise, not to specific columns
import psycopg2
import csv
conn_str="host='localhost' port='' "
query=''
cur.execute(query)
title=[i[0] for i in cur.description]
result=cur.fetchall()
with open (file,'a') as csvfile:
if result:
c=csvwriter(csvfile)
c.writerow(title)
c.writerows(result)
Existing Csv file :
a,b,c,d,e (columns)
1,2,3
4,5,6
No data in d and e columns
Required
a,b,c,d,e
1,2,3,x,y
4,5,6,p,q
Post script execution only d and e columns should be filled. The table also has data pertinent to those fields.
Try
import csv
with open('current.csv', 'r') as c:
reader = csv.reader(c)
extended_rows = []
for row in reader:
row.append('Data From DB1')
row.append('Data From DB2')
extended_rows.append(row)
with open('extended.csv', 'w') as e:
writer = csv.writer(e)
writer.writerows(extended_rows)
current.csv
A,B,C
D,E,f
extended.csv
A,B,C,Data From DB1,Data From DB2
D,E,f,Data From DB1,Data From DB2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.