我有一个程序,它只需要取两个文件,然后逐行比较它们。只要两个文件的行数相同,它就可以正常工作。我的问题是,如果文件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")
您应该捕获
IndexError
,然后停止比较也许你可以用^{} 。如果一个序列已用尽,它将发出一些填充值(默认情况下,
None
):编辑正如@danidee所指出的,Py3是
zip_longest
。你知道吗为什么不使用内置的^{} ,而不是重新发明轮子呢?下面是使用文档中的^{} 的示例:
相关问题 更多 >
编程相关推荐