Comparing two .txt files using difflib in Python Comparing two .txt files using difflib in Python python python

Comparing two .txt files using difflib in Python


For starters, you need to pass strings to difflib.SequenceMatcher, not files:

# Like sodifflib.SequenceMatcher(None, str1, str2)# Or just read the files indifflib.SequenceMatcher(None, file1.read(), file2.read())

That'll fix your error anyway. To get the first non-matching string, I'll direct you to the wonderful world of difflib documentation.


Here is a quick example of comparing the contents of two files using Python difflib...

import difflibfile1 = "myFile1.txt"file2 = "myFile2.txt"diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines())print ''.join(diff),


Are you sure both files exist ?

Just tested it and i get a perfect result.

To get the results i use something like:

import difflibdiff=difflib.ndiff(open(testFile).readlines(), open(comparisonFile).readlines())try:    while 1:        print diff.next(),except:    pass

the first character of each line indicates if they are different:eg.: '+' means the following line has been added, etc.