简体   繁体   English

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

[英]Appending data to existing columns in csv file

I am taking data from a table (Postgres) and trying to append to an existing file. 我从表(Postgres)中获取数据并尝试附加到现有文件。 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 : 现有的Csv文件:

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

No data in d and e columns d和e列中没有数据

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. 后脚本执行只应填写d和e列。 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 current.csv

A,B,C
D,E,f

extended.csv extended.csv

A,B,C,Data From DB1,Data From DB2
D,E,f,Data From DB1,Data From DB2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM