Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read two csv files and compare every line. If the lines match print both lines, if it isn't similar print invalid

Tags:

python

import csv

f1 = open("file1.csv")

f2 = open("file2.csv")

csv_f1 = csv.reader(f1)

csv_f2 = csv.reader(f2)

for row1 in csv_f1: 
    for row2 in csv_f2:
        if row1 == row2:
            print row1[0], row2[0]
        else:
            print row1[0], "Invalid"

this program isn't printing out row1, row2. It's just printing first line of file1 and invalid on the same line several times.

like image 805
Shairyar Shafqat Avatar asked Jan 05 '15 14:01

Shairyar Shafqat


1 Answers

You need to compare the corresponding rows, not each row with each row, which is what your code does right now.

from __future__ import print_function

import csv
import itertools
import sys

# Select the right function based on whether we are in Python 2 or 3.
if sys.version_info.major == 2:
    zip_longest = itertools.izip_longest
else:
    zip_longest = itertools.zip_longest

f1 = open("file1.csv")
f2 = open("file2.csv")

csv_f1 = csv.reader(f1)
csv_f2 = csv.reader(f2)

for row1, row2 in zip_longest(csv_f1, csv_f2):
    if row1 == row2:
        print(row1[0], row2[0])
    else:
        print(row1[0], "Invalid")
like image 88
nwk Avatar answered Nov 14 '22 23:11

nwk