others - python使用 difflib 比较2个.txt文件

我试图比较2个文本文件,并且输出第一个字符串,但遇到了一些困难,

当我尝试类似:


result = difflib.SequenceMatcher(None, testFile, comparisonFile)

我得到一个错误: object of type'file'has no len

时间:

首先,你需要将字符串传递给difflib.SequenceMatcher,而不是文件:


# Like so
difflib.SequenceMatcher(None, str1, str2)

# Or just read the files in
difflib.SequenceMatcher(None, file1.read(), file2.read())

这将会修复你的错误。

你确定这两个文件都存在?


import difflib

diff=difflib.ndiff(open(testFile).readlines(), open(comparisonFile).readlines())

try:
 while 1:
 print diff.next(),
except:
 pass

你根本不需要difflib,如果要逐行比较,请尝试以下操作:


test_lines = open("test.txt").readlines()
correct_lines = open("correct.txt").readlines()

for test, correct in zip(test_lines, correct_lines):
 if test != correct:
 print"Oh no! Expected %r; got %r." % (correct, test)
 break
else:
 len_diff = len(test_lines) - len(correct_lines)
 if len_diff > 0:
 print"Test file had too much data."
 elif len_diff < 0:
 print"Test file had too little data."
 else:
 print"Everything was correct!"

下面是使用python difflib比较两个文件内容的快速示例。


import difflib

file1 ="myFile1.txt"
file2 ="myFile2.txt"

diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines())
print ''.join(diff),

...