Sì, penso che l'hashing del file sarebbe il modo migliore se devi confrontare diversi file e memorizzare gli hash per un confronto successivo. Poiché l'hash può interferire, è possibile eseguire un confronto byte per byte a seconda del caso d'uso.
Generalmente il confronto byte per byte sarebbe sufficiente ed efficiente, che il modulo filecmp già fa + altre cose.
Vedere http://docs.python.org/library/filecmp.html ad es.
>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False
Velocità considerazione: Di solito, se solo due file devono essere confrontati, li hashing e confrontando loro sarebbe più lento, invece di semplice confronto byte per byte, se fatto in modo efficiente. per esempio. il codice sotto tenta di time hash vs byte per byte
Disclaimer: questo non è il miglior modo di cronometrare o di confrontare due algo. e c'è bisogno di miglioramenti ma dà un'idea approssimativa. Se pensi che dovrebbe essere migliorato, dimmi che lo cambierò.
import random
import string
import hashlib
import time
def getRandText(N):
return "".join([random.choice(string.printable) for i in xrange(N)])
N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)
def cmpHash(text1, text2):
hash1 = hashlib.md5()
hash1.update(text1)
hash1 = hash1.hexdigest()
hash2 = hashlib.md5()
hash2.update(text2)
hash2 = hash2.hexdigest()
return hash1 == hash2
def cmpByteByByte(text1, text2):
return text1 == text2
for cmpFunc in (cmpHash, cmpByteByByte):
st = time.time()
for i in range(10):
cmpFunc(randText1, randText2)
print cmpFunc.func_name,time.time()-st
e l'uscita è
cmpHash 0.234999895096
cmpByteByByte 0.0
fonte
2009-07-02 04:56:13
Questo è un duplicato di http://stackoverflow.com/questions/ 254350 – pufferfish