林一行比较两个文件

2024-09-21 01:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,它只需要取两个文件,然后逐行比较它们。只要两个文件的行数相同,它就可以正常工作。我的问题是,如果文件2的行数比文件1的行数多怎么办?或者反过来。当发生这种情况时,我得到IndexError:list索引超出范围错误。我该怎么做才能考虑到这一点?你知道吗

#Compares two files
def compare(baseline, newestFile):



    baselineHolder = open(baseline)
    newestFileHolder = open(newestFile)



    lines1 = baselineHolder.readlines()
    a = returnName(baseline)
    b = returnName(newestFile)


    for i,lines2 in enumerate(newestFileHolder):
        if lines2 != lines1[i]:
            add1 = i + 1
            print ("line ", add1, " in newestFile is different \n")
            print("TAKE A LOOK HERE----------------------TAKE A LOOK HERE")
            print (lines2)
        else:
            addRow = 1 + i
            print ("line  " + str(addRow) + " is identical")

Tags: 文件inislineopenprinttakebaseline
3条回答

您应该捕获IndexError,然后停止比较

    for i,lines2 in enumerate(newestFileHolder):
        try:
            if lines2 != lines1[i]:
                add1 = i + 1
                print ("line ", add1, " in newestFile is different \n")
                print("TAKE A LOOK HERE           TAKE A LOOK HERE")    
                print (lines2)
            else:
                addRow = 1 + i
                print ("line  " + str(addRow) + " is identical")
        except IndexError:
            print("Exit comparison")
            break

也许你可以用^{}。如果一个序列已用尽,它将发出一些填充值(默认情况下,None):

import itertools

for l, r in itertools.izip_longest(open('foo.txt'), open('bar.txt')):
    if l is None: # foo.txt has been exhausted
        ...
    elif r is None: # bar.txt has been exhausted
        ...
    else: # both still have lines - compare now the content of l and r
        ...

编辑正如@danidee所指出的,Py3是zip_longest。你知道吗

为什么不使用内置的^{},而不是重新发明轮子呢?下面是使用文档中的^{}的示例:

>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
...     sys.stdout.write(line)   
 - before.py
+++ after.py
@@ -1,4 +1,4 @@
-bacon
-eggs
-ham
+python
+eggy
+hamster
 guido

相关问题 更多 >

    热门问题