Compare two .txt files using if else in python

1

I want to compare two text files in Python. According to the result (equal / deferent), you must continue with a conditional. Searching on Google I found this code, but it does not return anything (TRUE / FALSE).

import filecmp
filecmp.cmp('txt/nuevo.txt', 'txt/master.txt')
    
asked by tomillo 26.04.2018 в 01:16
source

1 answer

1

Effectively filecmp.cmp return True if both files are considered equal and False otherwise.

The problem is that you are simply not using the return of the function at any time. You can assign the return to a variable:

iguales = filecmp.cmp('txt/nuevo.txt', 'txt/master.txt')
if iguales:
    print("Iguales")
else:
    print("Diferentes")

Or use the function directly in the conditional:

if filecmp.cmp('txt/nuevo.txt', 'txt/master.txt'):
    print("Iguales")
else:
    print("Diferentes")
  

Note: filecmp.cmp has a third parameter, shallow which by default is True . If this argument is True the comparison is made facing the exits of os.stat() , which is faster than comparing the content directly and that usually will be enough. If you pass it with value False if you are going to compare the contents of both files themselves.

    
answered by 26.04.2018 / 01:49
source