- What is difflib? What to do?
Difflib for the python standard library module, without having to install.
When the contrast between the text effect.
And strong support output more readable HTML document, similar to the diff command under Linux.
Very useful for version control. - Symbol appreciated
Symbol Meaning
'-' contained in the first row in the series, but not the second.
'+' Is contained in the second row in the series, but does not include the first one.
'' Series of the same two lines
'?' Incremental differences exist
'^' character differences
import difflib
text1 = ''' 1. Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Within last Complicated IS Better Complex.
'' '.Splitlines (keepends = False)
Print (text1) the separated multi-line text line by line, to return a list of end of line is not retained newline
text2 = ''' 1. Beautiful is better than ugly.
- Simple is better than complex.
- Complicated is better than complex.
- Within last nested IS Better Flat.
'' '.Splitlines (keepends = True)
Print (text2) # multiple lines of text separated by line, to return a list of reserved line feed end of the line
"" "
The splitlines () divided by rows
returns each row contains a list of elements as
parameters:
keepends = True reserved line breaks
keepends = False does not contain a newline
" ""
# linux inside achieve similar functionality diff command
#d = difflib.Differ ()
#Print ( ''. the Join (List (d.compare (text1, text2))))
D = difflib.HtmlDiff ()
the htmlContent = d.make_file (text1, text2)
#Print (the htmlContent)
with Open ( 'the diff .html ',' W ') AS F:
f.write (the htmlContent)
The contrast between linux file
First read out the contents of the file, and then can be treated according to the method described above:
import difflib
filename1 = '/tmp/passwd'
filename2 = '/tmp/passwd1'
with open(filename1) as f1,open(filename2) as f2:
content1 = f1.read().splitlines(keepends=True)
content2 = f2.read().splitlines(keepends=True)
d = difflib.HtmlDiff()
htmlContent = d.make_file(content1,content2)
with open('passwdDiff.html','w') as f:
f.write(htmlContent)