tran0191 0 Newbie Poster

I am doing a project where I read in a CSV file and I iterate through each row in the file. I then compare a specific column from each row, if a row with the specified column has the same value as another row with the specified column I would write those rows to a new CSV file. If they are different I would write those rows to a different CSV file.

So ultimately in the end I would parse the CSV file and any rows with the same column values would be in a the same CSV file.

Here is what I have so far in terms of code.

>>> import csv

>>> file = csv.reader(open('C/NEW.CSV','r'), delimiter=',')

>>> first = csv.writer(open('C://First.CSV','w'))

>>> second = csv.writer(open('C/fir.CSV','w'))

>>> header = file.next()

>>> for row in file:
... 	lon ="51"
…	lat =”45.9”
…	depth = “80”
... 	if row[3] == lat and row[4] == lon and row[5] == depth:
... 		first.writerow(row)
…		count = 1
... 	else:
... 		second.writerow(row)
…	lat = row[3]
... 	lon = row[4]
... 	depth = row[5]
>>>

The problem I am having is I dont want to hardcore the values lon, lat or depth because I will have to read in a different CSV file everytime and the values wont be the same. So i need a way to assign those values to the values in the very first row of the CSV file...

And I dont quite understand how this works either, I thought if you were to assign a variable at the beginning of a for loop and then change it at the end of the for loop, the next time it iterates through the loop the value would be set again to what it is initially set to instead of what you change it to at the end.

for ex:

for row in file:
lon = "51"

.....do some code

lon = row[4]


you would think that lon would always be 51 at the beginning of the next iteration, how does it change to row[4] everytime?

Anyways if anyone can help me with my problem it would be greatly appreciated.