需求:
需要判断文件是否被修改,注:其被修改的文件,大小无变化(kb级),文件不能打开,故想到这种方法。
源码:
import hashlib
import os, sys
def CalcSha1(filepath):
with open(filepath, 'rb') as f:
sha1obj = hashlib.sha1()
sha1obj.update(f.read())
hash = sha1obj.hexdigest()
print(hash)
return hash
def CalcMD5(filepath):
with open(filepath, 'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
print(hash)
return hash
if __name__ == "__main__":
if len(sys.argv) == 2:
hashfile = sys.argv[1]
if not os.path.exists(hashfile):
hashfile = os.path.join(os.path.dirname(__file__), hashfile)
if not os.path.exists(hashfile):
print("cannot found file")
else:
CalcMD5(hashfile)
else:
CalcMD5(hashfile)
# raw_input("pause")
else:
print("no filename")
# 5c98ebd0494934151f55cbd7ed9feb57305b3811
# 35306f3b296a458425f2aa1c9419401701c6526f
CalcSha1('a.txt')
# 338795c0fa8ab13e183d8347cf9c0fd0
# 35899beb60ab2406ef24ee7345081774
CalcMD5('a.txt')
小结
虽然修改后的文件的hush码有变化,但还是不明白sha1函数和md5函数打印的hush值的区别,之后再仔细研究~~~!奥利给!!!