Find Common Region In Two Csv File In Python
I have two CSV files with 10 columns each where the first column is called the 'Primary Key'. I need to use Python to find the common region between the two CSV files. For example
Solution 1:
index
is the iterator in your for
loop. Should you changed it inside the loop, it will be reassigned after each iteration.
Say, when index = 5
in your for
loop, and index += 1
was execute 3 times. Now index = 8
. But after this iteration ends, when your code go back to for
, index will be assigned to index x = 6
.
Try following example:
forindex in range(0,5):
print'iterator:', indexindex = index + 2print'index:', index
The output will be:
iterator: 0index: 2iterator: 1index: 3iterator: 2index: 4iterator: 3index: 5iterator: 4index: 6
To fix this issue, you might want to change your for
loop to while
loop
EDIT: If I didn't understand wrong, you were trying to find 'same' columns in two files and store them. If this is the case, actually your work can be done easily by using following code:
import csv # import csv module to read csv files
file1 = 'csv1.csv' # input file 1
file2 = 'csv2.csv' # input file 2
outfile = 'csv3.csv' # only have one output file since two output files will be the same
read1 = csv.reader(open(file1, 'r')) # readinput file 1write = csv.writer(open(outfile, 'w')) # write to output file
# for each row ininput file 1, compare it with each row ininput file 2
# if they are the same, write that row into output file
for row1 in read1:
read2 = csv.reader(open(file2, 'r'))
for row2 in read2:
if row1 == row2:
write.writerow(row1)
read1.close()
write.close()
Post a Comment for "Find Common Region In Two Csv File In Python"