两个txt文件是从数据库导出来的,含有主键。
从网上找了文件对比的方法:
MD5:将两个文件使用md5,如果两个文件的md5相等就说明两个文件内容相同。
cmpfile:python中的一个专门库比较两个文件
这两种均无法把两个文件中内容不同的部分保存下来,而且对于两个文件内容相同仅是顺序不同,也无法进行判断。
因此本人自己写了一个程序进行比较,因为txt文件中含有主键,所以借用字典的数据结构,key值保存主键。
三种方法的程序,如下所示:
import hashlib
def file_compare1(file):
md5=hashlib.md5()
with open(file1,"r") as f1:
while True:
b=f1.read(8096)
if not b:
break
md5.update(b.encode('utf-8'))
return md5.hexdigest()
import filecmp
def file_compare2(file1,file2):
result=filecmp.cmp(file1,file2)
return result
def file_compare3(file1,file2):
text_dict1={}
text_dict2={}
with open(file1,"r",encoding='gbk') as f1:
for line in f1:
#print(type(line)) #<class 'str'>
key=line[0:10]