Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

attributeerror - 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_learningonefirst_file.txt'
second_file = 'E:Elzero_learningsecond_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_learningoutput_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_learningcompare files.py", line 7, in <module>
    difference = difflib.HtmlDiff.make_file(first_file_lines ,second_file_lines ,first_file ,second_file )
  File "C:pythonPython39libdifflib.py", line 1764, in make_file
    return (self._file_template % dict(
AttributeError: 'list' object has no attribute '_file_template'
PS E:Elzero_learning> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...