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

后端 未结 8 630
我在风中等你
我在风中等你 2020-11-29 01:51

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

8条回答
  •  臣服心动
    2020-11-29 02:31

    I would use a hash of the file's contents using MD5.

    import hashlib
    
    def checksum(f):
        md5 = hashlib.md5()
        md5.update(open(f).read())
        return md5.hexdigest()
    
    def is_contents_same(f1, f2):
        return checksum(f1) == checksum(f2)
    
    if not is_contents_same('foo.txt', 'bar.txt'):
        print 'The contents are not the same!'
    

提交回复
热议问题