我正在尝试编写程序,查看两个文件,并创建一个新文件,显示哪些行不同。两个文件的行数相等,每行上都有数字1或-1,例如:
-1
1
1
-1
然而,到目前为止,我所做的代码认为每一行都是不同的,并将它们全部写入新文档:
f1 = open("file1", "r")
f2 = open("file2", "r")
fileOne = f1.readlines()
fileTwo = f2.readlines()
f1.close()
f2.close()
outFile = open("results.txt", "w")
x = 0
for i in fileOne:
if i != fileTwo[x]:
outFile.write(i+" <> "+fileTwo[x])
print i+" <> "+fileTwo[x]
x += 1
outFile.close()
试试这样:
with open("file1") as f1,open("file2") as f2:
for x,y in zip(f1,f2):
if x !=y :
print " dissimilar lines "
zip()
将从两个文件中获取单独的行,然后您可以比较它们:
的例子:
In [12]: a=[1,2,3]
In [13]: b=[4,2,6]
In [14]: for i,(x,y) in enumerate(zip(a,b)):
if x !=y :
print "line :{0} ==> comparing {1} and {2}".format(i,x,y)
line :0 ==> comparing 1 and 4
line :2 ==> comparing 3 and 6