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

yipeiwu_com5年前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做的数学四则运算_算术口算练习程序(后添加减乘除)

最近着迷上了 Python 用Python给小宝做的数学算数口算练习程序(2015年1月添加四则运算)! 给小宝做的口算游戏: #用Python给小宝做的数学算数口算练习程序(201...

python使用正则表达式的search()函数实现指定位置搜索功能

前面学习过search()可以从任意一个文本里搜索匹配的字符串,也就是说可以从任何位置里搜索到匹配的字符串。但是现实世界很复杂多变的,比如限定你只能从第100个字符的位置开始匹配,100...

python开发之anaconda以及win7下安装gensim的方法

一、推荐安装Anaconda 官方介绍:Anaconda is a completely free Python distribution (including for commerci...

教你一步步利用python实现贪吃蛇游戏

教你一步步利用python实现贪吃蛇游戏

0 引言 前几天,星球有人提到贪吃蛇,一下子就勾起了我的兴趣,毕竟在那个Nokia称霸的年代,这款游戏可是经典中的经典啊!而用Python(蛇)玩Snake(贪吃蛇),那再合适不过了&...

深入解析Python中的上下文管理器

1. 上下文管理器是什么? 举个例子,你在写Python代码的时候经常将一系列操作放在一个语句块中: (1)当某条件为真 – 执行这个语句块 (2)当某条件为真 – 循环执行这个语句块...