Oh Snap!

Please turnoff your ad blocking mode for viewing your site content

Hit enter after type your search item

Python 3 difflib Library Example Script to Compare Two Text Files Line by Line Full Tutorial For Beginners

/
/
/
12 Views

 

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

 

READ  Python 3 Github API Web Scraper or Crawler Script to Scrape User Profile and Repositories Details Using requests and json Modules Full Project For Beginners

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

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This div height required for enabling the sticky sidebar
Coding Shiksha 2020. All Rights Reserved.
Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :