我正在尝试比较行级别的两个csv文件。如果匹配字符串,则打印正确的字符串。
import csv
file1 = open('/a1.csv','rb')
file2 = open('/test.csv','rb')
myfile = csv.reader(file1, delimiter=',')
myfile1 = csv.reader(file2, delimiter=',')
for row in myfile:
for row1 in myfile1:
new=""
if row1[0] == row:
new = row[0]
else:
new = row1[0]
print new
a1.csv包含样本输入:
A,a,a1,a2
B,b,b1,b5
test.csv包含样本输入:
a
a!
如果字符串匹配,例如“a”==“A,a,a1,a2”那么我想打印'A'并且如果没有匹配,例如“a!” ==“A,a,a1,a2”然后需要打印'a!'
我的代码是打印“a”和“a!”没有比较的输出。这是比较字符串的错误方法吗?
答案 0 :(得分:0)
请尝试此操作(请注意in语句而不是' ==')另请注意打印逻辑已更改:
import csv
file1 = open('/a1.csv','rb')
file2 = open('/test.csv','rb')
a1 = csv.reader(file1, delimiter=',')
test = csv.reader(file2, delimiter=',')
for row1 in test:
new=""
found = False
for row in a1:
if row1[0] in row:
new = row[0]
found = True
if not found:
new = row1[0]
print new
file1.seek(0)