Compare md5 hashes of two files in python

前端 未结 2 2036
一整个雨季
一整个雨季 2020-12-17 01:11

I want to compare hashes of two files. But no matter if files are different or not, even with different hashes comparison results True

Here is the code:

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 01:47

    As a general rule Python methods follow the principle of command-query separation -- so that methods that modify the object (i.e. commands) return None. This includes, for example, list.sort, and dict.update. It is also true of the hasher1.update method. So

    a = hasher1.update(buf1)
    

    assigns None to a. Instead, use

    hasher1.update(buf1)
    a = hasher1.hexdigest()
    

    and similarly for b.


    import hashlib
    
    digests = []
    for filename in ['canvas.png', 'img5.png']:
        hasher = hashlib.md5()
        with open(filename, 'rb') as f:
            buf = f.read()
            hasher.update(buf)
            a = hasher.hexdigest()
            digests.append(a)
            print(a)
    
    print(digests[0] == digests[1])
    

提交回复
热议问题