[英]Python: Trouble with comparing two files and making a new file which shows the differences
我正在尝试编写一个程序,该程序查看两个文件并制作一个新文件,以显示哪些行不同。 这两个文件的行数相等,并且每行的数字都为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.