Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two files in python

Tags:

python

I have the following code. I have checked other links on stackoverflow, but they are slightly complicated than mine.

For now my text files have hello(in file1) and hell(in file2) as data.

I believe my logic is correct but I get the following error

TypeError: object of type '_io.TextIOWrapper' has no len()

Where am I going wrong?

def compareString(line1,line2): #sub function to compare strings of files
    i=0 #initial index
    while line1[i]==line2[i]: #compare each line until they are equal
        i=i+1
    if line1[i]!=line2[i]: #if unequal
        print('Mismatch at character ',i,line1[i]) #print error message

def compareMain(): #
    file1=input('Enter the name of the first file: ') #input file1 name
    file2=input('Enter the name of the second file: ') #input file2 name

    fp1=open(file1,'r') #open file1, reading mode
    fp2=open(file2,'r') #open file2, reading mode
    for line1 in range(len(fp1)): #Getting each line of file1
        for line2 in range(len(fp2)): #Getting each line of file2
            compareString(line1,line2) #Call compare function
    fp1.close() #Close file1
    fp2.close() #Close file2

compareMain() #Execute
like image 254
Jeff Benister Avatar asked Mar 25 '26 02:03

Jeff Benister


1 Answers

I would do it like this:

def compare_files():
    file1=input('Enter the name of the first file: ') #input file1 name
    file2=input('Enter the name of the second file: ') #input file2 name
    fp1=open(file1,'r') #open file1, reading mode
    fp2=open(file2,'r') #open file2, reading mode
    if (fp1.read() == fp2.read()):
        print("Files are the same")
    else:
        print("Files are not the same")

compare_files()

Method .read() will return content of the file. We get content of both files and then we compare contents of this files.

like image 54
golobitch Avatar answered Mar 26 '26 16:03

golobitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!