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脚本实现查找webshell的方法
Jul 31 Python
python实现得到一个给定类的虚函数
Sep 28 Python
Python编程实现生成特定范围内不重复多个随机数的2种方法
Apr 14 Python
PyQt5每天必学之滑块控件QSlider
Apr 20 Python
在cmd命令行里进入和退出Python程序的方法
May 12 Python
windows下python安装pip图文教程
May 25 Python
python把转列表为集合的方法
Jun 28 Python
python实现超级马里奥
Mar 18 Python
python 穷举指定长度的密码例子
Apr 02 Python
jupyter notebook清除输出方式
Apr 10 Python
filter使用python3代码进行迭代元素的实例详解
Dec 03 Python
python 如何在测试中使用 Mock
Mar 01 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
发挥语言的威力--融合PHP与ASP
2006/10/09 PHP
Apache中php.ini的设置方法
2013/02/28 PHP
Mac版PhpStorm之XAMPP整合apache服务器配置的图文教程详解
2016/10/13 PHP
详解PHP队列的实现
2019/03/14 PHP
Yii实现微信公众号场景二维码的方法实例
2020/08/30 PHP
用javascript实现的仿Flash广告图片轮换效果
2007/04/24 Javascript
每天一篇javascript学习小结(Array数组)
2015/11/11 Javascript
全面理解JavaScript中的继承(必看)
2016/06/16 Javascript
浅析JavaScript中命名空间namespace模式
2016/06/22 Javascript
jQuery实现页面点击后退弹出提示框的方法
2016/08/24 Javascript
基于JavaScript实现鼠标箭头移动图片跟着移动
2016/08/30 Javascript
js 获取图像缩放后的实际宽高,位置等信息
2017/03/07 Javascript
vue2.X组件学习心得(新手必看篇)
2017/07/05 Javascript
简单实现jquery隔行变色
2017/11/09 jQuery
VueJs使用Amaze ui调整列表和内容页面
2017/11/30 Javascript
vuex中的 mapState,mapGetters,mapActions,mapMutations 的使用
2018/04/13 Javascript
webpack4 升级迁移的实现
2018/09/12 Javascript
javascript 函数的暂停和恢复实例详解
2020/04/25 Javascript
[30:51]DOTA2上海特级锦标赛主赛事日 - 3 胜者组第二轮#1Liquid VS MVP.Phx第一局
2016/03/04 DOTA
python实现图片批量剪切示例
2014/03/25 Python
老生常谈Python基础之字符编码
2017/06/14 Python
python实现京东秒杀功能
2018/07/30 Python
Python列表推导式与生成器用法分析
2018/08/02 Python
python print输出延时,让其立刻输出的方法
2019/01/07 Python
Django中celery执行任务结果的保存方法
2019/07/12 Python
python3 常见解密加密算法实例分析【base64、MD5等】
2019/12/19 Python
pandas创建DataFrame的7种方法小结
2020/06/14 Python
纯HTML+CSS3制作导航菜单(附源码)
2013/04/24 HTML / CSS
canvas画图被放大且模糊的解决方法
2020/08/11 HTML / CSS
英国著名的小众美容品牌网站:Alyaka
2017/08/08 全球购物
汽车转让协议书
2015/01/29 职场文书
二手车转让协议书
2015/01/29 职场文书
幼儿园中班教师个人工作总结
2015/02/06 职场文书
2015年安全工作总结范文
2015/04/02 职场文书
离职信范文
2015/06/23 职场文书
分析并发编程之LongAdder原理
2021/06/29 Java/Android