Search code examples
python-3.xattributeerrordifflib

How do I compare two python scripts with the difflib library?


I want to compare two python scripts with the difflib library.

One of the scripts is working, the other one is not.

I used the following code to compare the two files:

import difflib 

first_file = 'E:\Elzero_learning\onefirst_file.txt'
second_file = 'E:\Elzero_learning\second_file.txt'
first_file_lines = open (first_file).readlines()
second_file_lines = open (second_file).readlines()
difference = difflib.HtmlDiff.make_file(first_file_lines ,second_file_lines ,first_file ,second_file )
difference_report = open("E:\Elzero_learning\output_file_1.html","w")
difference_report.write(difference)
difference_report.close()

However I receive this error traceback when executing the code:

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS E:\Elzero_learning> & C:/python/Python39/python.exe "e:/Elzero_learning/compare files.py"
Traceback (most recent call last):
  File "e:\Elzero_learning\compare files.py", line 7, in <module>
    difference = difflib.HtmlDiff.make_file(first_file_lines ,second_file_lines ,first_file ,second_file )
  File "C:\python\Python39\lib\difflib.py", line 1764, in make_file
    return (self._file_template % dict(
AttributeError: 'list' object has no attribute '_file_template'
PS E:\Elzero_learning> 

Solution

  • You need an instance of difflib.HtmlDiff on which to call make_file() so change:

    difference = difflib.HtmlDiff.make_file(...)
    

    to

    difference = difflib.HtmlDiff().make_file(...)
    

    which creates a difflib.HtmlDiff instance before calling its make_file() method.

    You might like to review the documentation for class difflib.HtmlDiff to see if there are any default parameters that you would want to set.