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历史天气采集的分析

分析历史天气的趋势。 先采集 代码: #-*- coding:utf-8 -*- import requests import random import MySQLdb im...

python采集百度百科的方法

本文实例讲述了python采集百度百科的方法。分享给大家供大家参考。具体如下: #!/usr/bin/python # -*- coding: utf-8 -*- #encoding...

django-filter和普通查询的例子

pythong在使用中,尤其是django的查询过程中插件还是不少的,最近发现了一个插件django-filter ,还挺好用的 1.最原始直接根据条件查询 def search(r...

python多线程操作实例

python多线程操作实例

一、python多线程 因为CPython的实现使用了Global Interpereter Lock(GIL),使得python中同一时刻只有一个线程在执行,从而简化了python解释...

Python使用email模块对邮件进行编码和解码的实例教程

解码邮件 python自带的email模块是个很有意思的东西,它可以对邮件编码解码,用来处理邮件非常好用。 处理邮件是一个很细致的工作,尤其是解码邮件,因为它的格式变化太多了,下面先看看...