相关疑难解决方法(0)

50
推荐指数
4
解决办法
3万
查看次数

比较python中的两个文件报告差异

我有两个名为"hosts"的文件(在不同的目录中)

我想用python比较它们,看看它们是否是IDENTICAL.如果它们不相同,我想在屏幕上打印差异.

到目前为止,我已经尝试过了

hosts0 = open(dst1 + "/hosts","r") 
hosts1 = open(dst2 + "/hosts","r")

lines1 = hosts0.readlines()

for i,lines2 in enumerate(hosts1):
    if lines2 != lines1[i]:
        print "line ", i, " in hosts1 is different \n"
        print lines2
    else:
        print "same"
Run Code Online (Sandbox Code Playgroud)

但是当我跑这个时,我得到了

File "./audit.py", line 34, in <module>
  if lines2 != lines1[i]:
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

这意味着其中一个主机拥有比另一个更多的线路.有没有更好的方法来比较2个文件并报告差异?

python comparison file

34
推荐指数
2
解决办法
7万
查看次数

标签 统计

file ×2

python ×2

compare ×1

comparison ×1