“Python-Pandas” Checking the Difference in Content of Two Text Files.

Python
higashi
higashi

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!!

 

Sponsored Links

Introduction of Sample Text File

This time, I use below text file for demonstration.

sample text file

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.

 

Sponsored Links

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.

 

Sponsored Links

Demonstration of Sample Code

So, let’s demonstrate!!

 

At first in the case of below.

These files are completely match.

sample text files (completely match)

By conducting the program, below result was shown.

program result (completely match)

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.

sample text (contain different point)

By conducting the program, below result was shown.

result of program (contain different point)

It tells me where the difference is without any problem.

 

higashi
higashi

It is very convenient for me.

That’s all. Thank you!!

コメント