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 相关文章推荐
在CentOS上配置Nginx+Gunicorn+Python+Flask环境的教程
Jun 07 Python
django实现同一个ip十分钟内只能注册一次的实例
Nov 03 Python
python虚拟环境迁移方法
Jan 03 Python
详解python使用turtle库来画一朵花
Mar 21 Python
django-初始配置(纯手写)详解
Jul 30 Python
Python爬虫使用代理IP的实现
Oct 27 Python
python求质数列表的例子
Nov 24 Python
Python小程序之在图片上加入数字的代码
Nov 26 Python
Python Sympy计算梯度、散度和旋度的实例
Dec 06 Python
python pptx复制指定页的ppt教程
Feb 14 Python
Python如何把十进制数转换成ip地址
May 25 Python
Python使用Pygame绘制时钟
Nov 29 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通过array_unshift函数添加多个变量到数组前端的方法
2015/03/18 PHP
php使用post数组的键值创建同名变量并赋值的方法
2015/04/03 PHP
PHP判断数组是否为空的常用方法(五种方法)
2017/02/08 PHP
PHP中ltrim()函数的用法与实例讲解
2019/03/28 PHP
浅谈laravel框架与thinkPHP框架的区别
2019/10/23 PHP
javaScript让文本框内的最后一个文字的后面获得焦点实现代码
2013/01/06 Javascript
jQuery实现购物车计算价格功能的方法
2015/03/25 Javascript
jQuery使用slideUp方法实现控制元素缓慢收起
2015/03/27 Javascript
nodejs修复ipa处理过的png图片
2016/02/17 NodeJs
新入门node.js必须要知道的概念(必看篇)
2016/08/10 Javascript
基于JavaScript实现的插入排序算法分析
2017/04/14 Javascript
jQuery Jsonp跨域模拟搜索引擎
2017/06/17 jQuery
详解Javascript 中的 class、构造函数、工厂函数
2017/12/20 Javascript
浅谈Vue响应式(数组变异方法)
2018/05/07 Javascript
微信小程序自定义toast的实现代码
2018/11/16 Javascript
使用Vue.js 和Chart.js制作绚丽多彩的图表
2019/06/15 Javascript
layui+jquery支持IE8的表格分页方法
2019/09/28 jQuery
extjs图表绘制之条形图实现方法分析
2020/03/06 Javascript
python 字典中文key处理,读取,比较方法
2018/07/06 Python
在linux下实现 python 监控usb设备信号
2019/07/03 Python
Django+zTree构建组织架构树的方法
2019/08/21 Python
python脚本实现mp4中的音频提取并保存在原目录
2020/02/27 Python
django使用F方法更新一个对象多个对象字段的实现
2020/03/28 Python
浅谈Python里面None True False之间的区别
2020/07/09 Python
CSS3 filter(滤镜)实现网页灰色或者黑色模式的代码
2020/11/30 HTML / CSS
HTML5利用约束验证API来检查表单的输入数据的代码实例
2016/12/20 HTML / CSS
俄罗斯建筑和装饰材料在线商店:Stroilandia
2020/07/25 全球购物
计算机本科生自荐信
2013/10/15 职场文书
护士自荐信
2013/10/25 职场文书
回门宴答谢词
2014/01/13 职场文书
创先争优承诺书范文
2014/03/31 职场文书
个人学习总结范文
2015/02/15 职场文书
祝福语集锦:送给闺蜜的生日祝福语
2019/10/08 职场文书
MIME类型中application/xml与text/xml的区别介绍
2022/01/18 HTML / CSS
vue项目proxyTable配置和部署服务器
2022/04/14 Vue.js
python 判断字符串当中是否包含字符(str.contain)
2022/06/01 Python