

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to compare two different files line by line in Python?
The Python standard library has a module specifically for the purpose of finding diffs between strings/files. To get a diff using the difflib library, you can simply call the united_diff function on it. For example, Lets say you have 2 files, file1 and file2 with the following content −
file1: Hello People of the world file2: Hello People from India
Example
Now to take their diff use the following code −
import difflib with open('file1') as f1: f1_text = f1.read() with open('file2') as f2: f2_text = f2.read() # Find and print the diff: for line in difflib.unified_diff(f1_text, f2_text, fromfile='file1', tofile='file2', lineterm=''): print line
Output
This will give the output −
--- file1 +++ file2 @@ -1,5 +1,4 @@ Hello People -of -the -world +from +India
- Related Questions & Answers
- How to compare two sorted files line by line in the Linux system?
- How to read complete text file line by line using Python?
- Compare two int arrays in a single line in Java
- Compare two short arrays in a single line in Java
- Compare two double arrays in a single line in Java
- Compare two long arrays in a single line in Java
- Compare two float arrays in a single line in Java
- Compare two char arrays in a single line in Java
- Compare two-byte arrays in a single line in Java
- How to compare files in Python
- Read file line by line using C++
- How to execute Python multi-line statements in the one-line at command-line?
- Print level order traversal line by line in C++ Programming.
- Swap two variables in one line in using Python?
- C program to compare two files and report mismatches
Advertisements