Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, is there a concise way of comparing whether the contents of two text files are the same?

I don't care what the differences are. I just want to know whether the contents are different.

like image 584
Corey Trager Avatar asked Oct 31 '08 17:10

Corey Trager


People also ask

How can I tell if two text files are the same?

Probably the easiest way to compare two files is to use the diff command. The output will show you the differences between the two files.


2 Answers

The low level way:

from __future__ import with_statement with open(filename1) as f1:    with open(filename2) as f2:       if f1.read() == f2.read():          ... 

The high level way:

import filecmp if filecmp.cmp(filename1, filename2, shallow=False):    ... 
like image 137
Federico A. Ramponi Avatar answered Sep 28 '22 11:09

Federico A. Ramponi


If you're going for even basic efficiency, you probably want to check the file size first:

if os.path.getsize(filename1) == os.path.getsize(filename2):   if open('filename1','r').read() == open('filename2','r').read():     # Files are the same. 

This saves you reading every line of two files that aren't even the same size, and thus can't be the same.

(Even further than that, you could call out to a fast MD5sum of each file and compare those, but that's not "in Python", so I'll stop here.)

like image 37
Rich Avatar answered Sep 28 '22 10:09

Rich