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 相关文章推荐
Django中使用group_by的方法
May 26 Python
基于wxpython实现的windows GUI程序实例
May 30 Python
对pandas读取中文unicode的csv和添加行标题的方法详解
Dec 12 Python
python实现批量视频分帧、保存视频帧
May 31 Python
Python用字典构建多级菜单功能
Jul 11 Python
基于python的itchat库实现微信聊天机器人(推荐)
Oct 29 Python
Python使用微信接入图灵机器人过程解析
Nov 04 Python
python 实现提取log文件中的关键句子,并进行统计分析
Dec 24 Python
你可能不知道的Python 技巧小结
Jan 29 Python
Matplotlib使用字符串代替变量绘制散点图的方法
Feb 17 Python
用python写PDF转换器的实现
Oct 29 Python
Python 用户输入和while循环的操作
May 23 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
discuz论坛 用户登录 后台程序代码
2008/11/27 PHP
利用Memcached在php下实现session机制 替换PHP的原生session支持
2010/08/21 PHP
php源代码安装常见错误与解决办法分享
2013/05/28 PHP
php中的常用魔术方法总结
2013/08/02 PHP
PHP使用pcntl_fork实现多进程下载图片的方法
2014/12/16 PHP
php简单实现数组分页的方法
2016/04/30 PHP
iOS10推送通知开发教程
2016/09/19 PHP
ThinkPHP 3.2.3实现页面静态化功能的方法详解
2017/08/03 PHP
Thinkphp页面跳转设置跳转等待时间的操作
2019/10/16 PHP
RR vs IO BO3 第二场2.13
2021/03/10 DOTA
自己编写的支持Ajax验证的JS表单验证插件
2015/05/15 Javascript
javascript实现的淘宝旅行通用日历组件用法实例
2015/08/03 Javascript
jqTransform美化表单
2015/10/10 Javascript
javascript中window.open在原来的窗口中打开新的窗口(不同名)
2015/11/15 Javascript
webpack入门必知必会
2017/01/16 Javascript
AngularJS1.X学习笔记2-数据绑定详解
2017/04/01 Javascript
详解RequireJS按需加载样式文件
2017/04/12 Javascript
JavaScript原生实现观察者模式的示例
2017/12/15 Javascript
解决angular双向绑定无效果,ng-model不能正常显示的问题
2018/10/02 Javascript
JS栈stack类的实现与使用方法示例
2019/01/31 Javascript
JavaScript基础之this和箭头函数详析
2019/09/05 Javascript
vue项目前端微信JSAPI与外部H5支付相关实现过程及常见问题
2020/04/14 Javascript
基于JS实现快速读取TXT文件
2020/08/25 Javascript
python聊天程序实例代码分享
2013/11/18 Python
Python实现文件复制删除
2016/04/19 Python
python抓取网页中链接的静态图片
2018/01/29 Python
树莓派使用python-librtmp实现rtmp推流h264的方法
2019/07/22 Python
Python实现投影法分割图像示例(一)
2020/01/17 Python
Python: tkinter窗口屏幕居中,设置窗口最大,最小尺寸实例
2020/03/04 Python
Python定义函数实现累计求和操作
2020/05/03 Python
Python实现上下文管理器的方法
2020/08/07 Python
初三物理教学反思
2014/01/21 职场文书
工商治理实习生的自我评价分享
2014/02/20 职场文书
教师节演讲稿
2014/05/06 职场文书
分布式锁为什么要选择Zookeeper而不是Redis?看完这篇你就明白了
2021/05/21 Redis
详解Go语言Slice作为函数参数的使用
2021/07/02 Golang