Pkde Pkde - 1 year ago 148
Python Question

How to add data to the new column in existing CSV using Python script


2 things i am trying to do as per below code

1) write data in column 2,3,4 and 8 of file1 to a new file.

2) data in 1st column(copied in new file)should be searched file2. if found,pick the data in 3rd column of same row of file 2 and write the same to the new column of new file.

point 1 is working fine..finding issue in getting output as per 2nd point

import csv

f1 = csv.reader(open("C:/Users/file1.csv","rb"))
f2 = csv.writer(open("C:/Users/newfile.csv","wb"))
f3 = csv.reader(open("C:/Users/file2.csv","rb"))

for row in f1:

if not row[0].startswith("-"):


var1 = row[1]

for row in f3:

if var1 in row:


Answer Source

I suspect that your re-use of the "row" variable name in the second for loop is clobbering the one held in "var1". I would always steer clear of that kind of recycling of variable names in nested loops.

for row_f1 in f1:

    if not row_f1[0].startswith("-"):


        var1 = row_f1[1]

        for row_f3 in f3:

            if var1 in row_f3:


However, I don't know that that append would do what you need, as f2 will have no append method, as far as I can see. From your use of .append, it looks like you wanted to put the elements from f1 into a list

for row_f1 in f1:

    if not row_f1[0].startswith("-"):

        temp_list = [row_f1[1],row_f1[2],row_f1[3],row_f1[7]]

        for row_f3 in f3:

            if temp_list[0] in row_f3:


Though your explanation of what you want to achieve isn't completely clear to me.

EDIT: I think Kristof's solution is far better, I was just trying to arrive at a solution that required minimal changes to your existing code. If you provided an example of what you expect your output to be with given inputs, that would definitely clarify things.