Python判断两个文件是否相同与两个文本进行相同项筛选的方法
python判断两个文件是否相同
importhashlib defgetHash(f): line=f.readline() hash=hashlib.md5() while(line): hash.update(line) line=f.readline() returnhash.hexdigest() defIsHashEqual(f1,f2): str1=getHash(f1) str2=getHash(f2) returnstr1==str2 if__name__=='__main__': f1=open("D:/2.iso","rb") f2=open("E:/wenjian/1.iso","rb") printIsHashEqual(f1,f2)
计算2个文件的MD5值,大文件计算较慢
python对两个文本进行相同项筛选
importos importos.pathasosp deffilter(path): file_path=osp.join(path,'index.txt') ifosp.exists(file_path): returnfile_path index_file=open(file_path,'a+') ifnotos.path.isdir(path):#判断path是否为路径 return forroot,dirs,listinos.walk(path): foriinlist: dir=os.path.join(root,i)#将分离的部分组成一个路径名 #ifos.path.getsize(dir)<60000:#获取文件大小 #os.remove(dir)#删除文件 print(i) index_file.write(i+'\n') index_file.close() defcompare(path): file=osp.join(path,'label.txt') file_path=osp.join(path,'index.txt') withopen(file_path,'r')asfile1: withopen(file,'r')asfile2: same=set(file1).intersection(file2) same.discard('\n') withopen('some_output_file.txt','w')asfile_out: forlineinsame: file_out.write(line) file_out.close() filter(r'D:\Desktop\jiaoben\ci') compare(r'D:\Desktop\jiaoben\ci')
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接