Python 3 difflib Library Example Script to Compare Two Text Files Line by Line Full Tutorial For Beginners
Welcome folks today in this post we will be comparing two text files
line by line using difflib library in python. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the following library using the pip
command as shown below
pip install difflib
After installing this library you need to create an app.py
file and copy paste the following code
Method 1: Using unified_diff()
app.py
# Importing difflib
import difflib
with open('file1.txt') as file_1:
file_1_text = file_1.readlines()
with open('file2.txt') as file_2:
file_2_text = file_2.readlines()
# Find and print the diff:
for line in difflib.unified_diff(
file_1_text, file_2_text, fromfile='file1.txt',
tofile='file2.txt', lineterm=''):
print(line)
Now just create two text files
as shown below and then we will compare it line by line
file1.txt
this is
the first
file in text1
using python
file2.txt
this is
the second
file in text2
using python
Now if we execute the python
script by typing the below command
python app.py