Hi, I’m higashi.
This page introduces how to check the difference in content of two text files.
Not only checking the difference, but also it can indicate the different contents.
For example, simulation tool often designate the simulation condition by using text file.
And we have to check the simulation conditions is same or not sometimes.
The program shown this page can use in these situations.
So, let’s get stated!!
Introduction of Sample Text File
This time, I use below text file for demonstration.
It has only 4 rows, but the program can accommodate any number of lines.
Let’s prepare another one of these text files and compare this for each case where there is an exact match and each case and where there are unmatched lines.
Sample Code of Checking Difference of Two Text Files
The sample code is shown below.
import pandas as pd
txt1='C:/Users/Desktop/study_python/test108/folder1/sample1.txt'
txt2='C:/Users/Desktop/study_python/test108/folder2/sample2.txt'
txt1=pd.read_csv(txt1, header=None)
txt2=pd.read_csv(txt2, header=None)
counter=0
for i in range(len(txt1)):
if txt1[0][i] != txt2[0][i]:
print('row'+str(i)+' Not equal')
print('txt1 '+txt1[0][i])
print('txt2 '+txt2[0][i])
counter+=1
if counter==0:
print('Equal')
Just you should do is only designate the file path of two files to 2nd,3rd lines.
In the case no difference it will display “Equal” and the other case display the difference content of text file.
Demonstration of Sample Code
So, let’s demonstrate!!
At first in the case of below.
These files are completely match.
By conducting the program, below result was shown.
Next I try this version.
3rd line is different.
*In the python program, first line as count number zero, so 3rd line of text will convert to 2nd line on python.
By conducting the program, below result was shown.
It tells me where the difference is without any problem.
It is very convenient for me.
That’s all. Thank you!!
コメント