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"
此程序未打印出row1,row2。它只是打印file1的第一行,并且在同一行上多次无效。
答案 0 :(得分:6)
您需要比较相应的行,而不是每行与行进行比较,这就是您的代码现在所做的。
import csv
import itertools
f1 = open("file1.csv")
f2 = open("file2.csv")
csv_f1 = csv.reader(f1)
csv_f2 = csv.reader(f2)
for row1,row2 in itertools.zip_longest(csv_f1, csv_f2):
if row1 == row2:
print row1, row2
else:
print row1, "Invalid"
答案 1 :(得分:1)
root1
,并与文件2进行比较,即使用相同的密钥与root2
进行比较。代码:
import csv
with open("/home/infogrid/Desktop/file1.csv", "rb") as fp1:
root = csv.reader(fp1,)
root1 = {}
for i in root:
root1[root.line_num] = i
with open("/home/infogrid/Desktop/file2.csv", "rb") as fp1:
root = csv.reader(fp1,)
root2 = {}
for i in root:
root2[root.line_num] = i
for i in root1:
try:
if root1[i]==root2[i]:
print root1[i], root1[i]
else:
print root1[i], "Invalid"
except:
print root1[i], "Invalid"
输出:
['test1', 'test3', 'test4'] ['test1', 'test3', 'test4']
['test1', 'test5', 'test4'] Invalid
['test1', 'test3', 'test4'] ['test1', 'test3', 'test4']
['test1', 'test3', 'test4'] Invalid