将数据追加到csv文件中的现有列

时间:2019-03-27 13:15:24

标签: python csv psycopg2

我正在从表(Postgres)中获取数据并尝试附加到现有文件中。要求是将数据插入相应的列

我只知道逐行追加,不追加到特定列

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)

现有的Csv文件:

a,b,c,d,e (columns)
1,2,3
4,5,6

d和e列中没有数据

必需

a,b,c,d,e 
1,2,3,x,y
4,5,6,p,q

后脚本执行仅应填充d和e列。该表还具有与这些字段相关的数据。

1 个答案:

答案 0 :(得分:0)

尝试

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