Python判断两个文件是否相同与两个文本进行相同项筛选的方法

yipeiwu_com6年前Python基础

python判断两个文件是否相同

import hashlib
def getHash(f):
  line=f.readline()
  hash=hashlib.md5()
  while(line):
    hash.update(line)
    line=f.readline()
  return hash.hexdigest()
def IsHashEqual(f1,f2):
  str1=getHash(f1)
  str2=getHash(f2)
  return str1==str2
if __name__ == '__main__':
  f1=open("D:/2.iso","rb")
  f2=open("E:/wenjian/1.iso","rb")
  print IsHashEqual(f1,f2)

计算2个文件的MD5值,大文件计算较慢

python对两个文本进行相同项筛选

import os
import os.path as osp
def filter(path):
  file_path = osp.join(path, 'index.txt')
  if osp.exists(file_path):
    return file_path
  index_file = open(file_path, 'a+')
  if not os.path.isdir(path):  #判断path是否为路径 
    return  
  for root, dirs, list in os.walk(path):
    for i in list: 
      dir = os.path.join(root, i)  #将分离的部分组成一个路径名 
      #if os.path.getsize(dir) < 60000:  #获取文件大小 
        #os.remove(dir)       #删除文件 
      print (i)
      index_file.write(i+'\n')
  index_file.close()    
def compare(path):
  file=osp.join(path, 'label.txt')
  file_path = osp.join(path, 'index.txt')
  with open(file_path, 'r') as file1:
     with open(file, 'r') as file2:
       same = set(file1).intersection(file2)
  same.discard('\n')
  with open('some_output_file.txt', 'w') as file_out:
     for line in same:
       file_out.write(line)
  file_out.close()
filter(r'D:\Desktop\jiaoben\ci')
compare(r'D:\Desktop\jiaoben\ci')

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

Python安装官方whl包和tar.gz包的方法(推荐)

Windows环境:   安装whl包:pip install wheel    ->    pip install&n...

利用python生成一个导出数据库的bat脚本文件的方法

实例如下: # 环境: python3.x def getExportDbSql(db, index): # 获取导出一个数据库实例的sql语句 sql = 'mysqldu...

Python的缺点和劣势分析

Python的短板 虽然Python拥有很多优点,但没有哪种编程语言能够胜任所有工 作,因此Python并不能完美地满足一切需求。如果要确定Python是否适 用于当前场景,还需要了解...

Python功能键的读取方法

本文实例讲述了Python功能键的读取方法。分享给大家供大家参考。具体分析如下: 先getch一下得到a,如果等于0或者224,就说明是功能键,再getch下一个得到b,那么这个功能键的...

django创建简单的页面响应实例教程

django创建简单的页面响应实例教程

首先 编辑views.py文件 每个响应对应一个函数 函数必须返回一个响应 函数必须存在一个参数 一般约定为request 每个响应函数 对应一个URL from django...