想要比较两个文件内容是否相同,逐行读取,然后字符比较,方法可行,但效率太低
MD5是一种加密技术,快速取得任意字符或文件的指纹,无需详细了解文件内容本身
参考资料
代码实现
# !/usr/bin/python3
# coding: utf-8
import hashlib
import os
# get file's md5
def md5(path):
if not os.path.isfile(path):
return None
try:
hash = hashlib.md5()
f = open(path, "rb")
while True:
b = f.read(1024)
if not b:
break
hash.update(b)
f.close()
return hash.hexdigest()
except:
return None
def diff(file1, file2):
hash1 = md5(file1)
hash2 = md5(file2)
if hash1 is None:
if hash2 is None:
return False
else:
return True
else:
if hash2 is None:
return True
return False if hash1 == hash2 else True