python查找指定具有相同内容文件的方法


Posted in Python onJune 28, 2015

本文实例讲述了python查找指定具有相同内容文件的方法。分享给大家供大家参考。具体如下:

python代码用于查找指定具有相同内容的文件,可以同时指定多个目录
调用方式:python doublesdetector.py c:\;d:\;e:\ > doubles.txt

# Hello, this script is written in Python - http://www.python.org
# doublesdetector.py 1.0p
import os, os.path, string, sys, sha
message = """
doublesdetector.py 1.0p
This script will search for files that are identical
(whatever their name/date/time).
 Syntax : python %s <directories>
   where <directories> is a directory or a list of directories
   separated by a semicolon (;)
Examples : python %s c:\windows
      python %s c:\;d:\;e:\ > doubles.txt
      python %s c:\program files > doubles.txt
This script is public domain. Feel free to reuse and tweak it.
The author of this script Sebastien SAUVAGE <sebsauvage at sebsauvage dot net>
http://sebsauvage.net/python/
""" % ((sys.argv[0], )*4)
def fileSHA ( filepath ) :
  """ Compute SHA (Secure Hash Algorythm) of a file.
    Input : filepath : full path and name of file (eg. 'c:\windows\emm386.exe')
    Output : string : contains the hexadecimal representation of the SHA of the file.
             returns '0' if file could not be read (file not found, no read rights...)
  """
  try:
    file = open(filepath,'rb')
    digest = sha.new()
    data = file.read(65536)
    while len(data) != 0:
      digest.update(data)
      data = file.read(65536)
    file.close()
  except:
    return '0'
  else:
    return digest.hexdigest()
def detectDoubles( directories ):
  fileslist = {}
  # Group all files by size (in the fileslist dictionnary)
  for directory in directories.split(';'):
    directory = os.path.abspath(directory)
    sys.stderr.write('Scanning directory '+directory+'...')
    os.path.walk(directory,callback,fileslist)
    sys.stderr.write('\n')
  sys.stderr.write('Comparing files...')
  # Remove keys (filesize) in the dictionnary which have only 1 file
  for (filesize,listoffiles) in fileslist.items():
    if len(listoffiles) == 1:
      del fileslist[filesize]
  # Now compute SHA of files that have the same size,
  # and group files by SHA (in the filessha dictionnary)
  filessha = {}
  while len(fileslist)>0:
    (filesize,listoffiles) = fileslist.popitem()
    for filepath in listoffiles:
      sys.stderr.write('.')
      sha = fileSHA(filepath)
      if filessha.has_key(sha):
        filessha[sha].append(filepath)
      else:
        filessha[sha] = [filepath]
  if filessha.has_key('0'):
    del filessha['0']
  # Remove keys (sha) in the dictionnary which have only 1 file
  for (sha,listoffiles) in filessha.items():
    if len(listoffiles) == 1:
      del filessha[sha]
  sys.stderr.write('\n')
  return filessha
def callback(fileslist,directory,files):
  sys.stderr.write('.')
  for fileName in files:
    filepath = os.path.join(directory,fileName)
    if os.path.isfile(filepath):
      filesize = os.stat(filepath)[6]
      if fileslist.has_key(filesize):
        fileslist[filesize].append(filepath)
      else:
        fileslist[filesize] = [filepath]
if len(sys.argv)>1 :
  doubles = detectDoubles(" ".join(sys.argv[1:]))
  print 'The following files are identical:'
  print '\n'.join(["----\n%s" % '\n'.join(doubles[filesha]) for filesha in doubles.keys()])
  print '----'
else:
  print message

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python调用java模块SmartXLS和jpype修改excel文件的方法
Apr 28 Python
Django rest framework实现分页的示例
May 24 Python
Python使用装饰器模拟用户登陆验证功能示例
Aug 24 Python
python/sympy求解矩阵方程的方法
Nov 08 Python
python微信好友数据分析详解
Nov 19 Python
Python小游戏之300行代码实现俄罗斯方块
Jan 04 Python
pyqt实现.ui文件批量转换为对应.py文件脚本
Jun 19 Python
dpn网络的pytorch实现方式
Jan 14 Python
PyTorch实现重写/改写Dataset并载入Dataloader
Jul 14 Python
python3.8动态人脸识别的实现示例
Sep 21 Python
基于Python的身份证验证识别和数据处理详解
Nov 14 Python
Python Parser的用法
May 12 Python
python中getaddrinfo()基本用法实例分析
Jun 28 #Python
python实现搜索指定目录下文件及文件内搜索指定关键词的方法
Jun 28 #Python
分析用Python脚本关闭文件操作的机制
Jun 28 #Python
python实现linux下使用xcopy的方法
Jun 28 #Python
自动化Nginx服务器的反向代理的配置方法
Jun 28 #Python
python读取TXT到数组及列表去重后按原来顺序排序的方法
Jun 26 #Python
在Python中使用zlib模块进行数据压缩的教程
Jun 26 #Python
You might like
通过curl模拟post和get方式提交的表单类
2014/04/23 PHP
php检测文件编码的方法示例
2014/04/25 PHP
PHP正则+Snoopy抓取框架实现的抓取淘宝店信誉功能实例
2017/05/17 PHP
JavaScript类型转换方法及需要注意的问题小结(挺全面)
2010/11/11 Javascript
javascript使用中为什么10..toString()正常而10.toString()出错呢
2013/01/11 Javascript
读取input:file的路径并显示本地图片的方法
2013/09/23 Javascript
js实现页面跳转的五种方法推荐
2016/03/10 Javascript
JS封装的选项卡TAB切换效果示例
2016/09/20 Javascript
基于Marquee.js插件实现的跑马灯效果示例
2017/01/25 Javascript
Angular动态添加、删除输入框并计算值实例代码
2017/03/29 Javascript
JQuery和html+css实现带小圆点和左右按钮的轮播图实例
2017/07/22 jQuery
vue中的计算属性的使用和vue实例的方法示例
2017/12/04 Javascript
JS实现登录页密码的显示和隐藏功能
2017/12/06 Javascript
微信公众号服务器验证Token步骤图解
2019/12/30 Javascript
详解JavaScript作用域、作用域链和闭包的用法
2020/09/03 Javascript
python 二维矩阵转三维矩阵示例
2019/11/30 Python
pycharm 中mark directory as exclude的用法详解
2020/02/14 Python
Python3与fastdfs分布式文件系统如何实现交互
2020/06/23 Python
Python如何爬取51cto数据并存入MySQL
2020/08/25 Python
HTML5 Canvas draw方法制作动画效果示例
2013/07/11 HTML / CSS
澳大利亚免息网上购物:Shop Zero
2016/09/17 全球购物
海外淘书首选:AbeBooks
2017/07/31 全球购物
100%植物性、有机、即食餐:Sakara Life
2018/10/25 全球购物
党章学习思想汇报
2014/01/14 职场文书
小学生美德少年事迹
2014/02/02 职场文书
酒店端午节促销方案
2014/02/18 职场文书
爱岗敬业演讲稿
2014/05/05 职场文书
师德师风个人自我剖析材料
2014/09/27 职场文书
2014年学生会干事工作总结
2014/11/07 职场文书
评职称个人总结
2015/03/05 职场文书
公司表扬信格式
2015/05/04 职场文书
改进工作作风心得体会
2016/01/23 职场文书
apache基于端口创建虚拟主机的示例
2021/04/24 Servers
HTML5页面音频自动播放的实现方式
2021/06/21 HTML / CSS
灵能百分百第三季什么时候来?
2022/03/15 日漫
漫画「日和酱的要求是绝对的」第3卷封面公开
2022/03/21 日漫