逐行比较2个文件

时间:2013-03-24 18:05:09

标签: python python-2.7

我有以下表格的2个文件:

file1:
work1
7 8 9 10 11
1 2 3 4  5
6 7 8 9  10

file2:
work2
2 3 4 5 5
2 4 7 8 9
work1
7 8 9 10 11
1 2 4 4  5
6 7 8 9  10
work3
1 7 8 9 10

现在我想比较文件和标题(work1)相等的地方..我想比较后续部分并打印找到差异的行。 E.g。

 work1 (file1)
7 8 9 10 11
1 2 3 4  5
6 7 8 9  10

work1 (file2)
7 8 9 10 11
1 2 4 4  5
6 7 8 9  10

现在我要打印出现差异的行,即“1 2 4 4 5”

为此,我编写了以下代码:

with open("file1",) as r, open("file2") as w:
    for line in r:
        if "work1" in line:
            for line1 in w:
                if "work1" in line1:
                        print "work1"

然而,从这里开始,我很困惑,我怎么能平行地阅读这两个文件。有人可以帮我解决这个问题......因为我在比较“work1”之后没有得到,我应该如何并行阅读文件

2 个答案:

答案 0 :(得分:1)

你可能想在Python中试用itertools模块。 它包含一个名为izip的函数,它可以执行您需要的操作,以及一个名为islice的函数。您可以遍历第二个文件,直到找到所需的标题,然后可以将标题切片。

这是一些代码。

from itertools import *    

w = open('file2')
for (i,line) in enumerate(w):
  if "work1" in line:
    iter2 = islice(open('file2'), i, None, 1) # Starts at the correct line

f = open('file1')
for (line1,line2) in izip(f,iter2):
  print line1, line2 # Place your comparisons of the two lines here.

现在你可以保证,在循环的第一次运行中,你将在两行上获得“work1”。之后你可以比较。由于fw短,迭代器会耗尽自己并在f结束后停止。

希望我能解释清楚。

编辑:添加了导入声明。

编辑:我们需要重新打开file2。这是因为在Python中迭代遍历迭代会消耗iterable。所以,我们需要将一个全新的版本传递给islice,这样才有效!

答案 1 :(得分:0)

with open('f1.csv') as f1, open('f2.csv') as f2 :
    i=0
    break_needed = False
    while True :
        r1, r2 = f1.readline(), f2.readline()
        if len(r1) == 0 :
            print "eof found for f1"
            break_needed = True
        if len(r2) == 0 :
            print "eof found for f2"
            break_needed = True
        if break_needed : 
            break
        i += 1
        if r1 != r2 :
            print " line %i"%i
            print "file 1 : " + r1
            print "file 2 : " + r2
相关问题