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之不要红头文件(1)
Sep 28 Python
使用grappelli为django admin后台添加模板
Nov 18 Python
Python实现的数据结构与算法之队列详解
Apr 22 Python
Python字符串详细介绍
May 09 Python
Python内建数据结构详解
Feb 03 Python
VSCode下配置python调试运行环境的方法
Apr 06 Python
opencv与numpy的图像基本操作
Mar 08 Python
python调用API接口实现登陆短信验证
May 10 Python
使用Python解析Chrome浏览器书签的示例
Nov 13 Python
Django websocket原理及功能实现代码
Nov 14 Python
python3中布局背景颜色代码分析
Dec 01 Python
这样写python注释让代码更加的优雅
Jun 02 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
PHILIPS AE3805收音机的分析打磨
2021/03/02 无线电
在PHP中养成7个面向对象的好习惯
2010/01/28 PHP
php中通过正则表达式下载内容中的远程图片的函数代码
2012/01/10 PHP
Laravel学习教程之View模块详解
2017/09/18 PHP
php微信开发之关注事件
2018/06/14 PHP
PHP pthreads v3在centos7平台下的安装与配置操作方法
2020/02/21 PHP
javascript XML数据显示为HTML一例
2008/12/23 Javascript
ext 代码生成器
2009/08/07 Javascript
当json键为数字时的取值方法解析
2013/11/15 Javascript
jquery访问ashx文件示例代码
2014/08/11 Javascript
分享javascript、jquery实用代码段
2016/10/20 Javascript
Webpack按需加载打包chunk命名的方法
2019/09/22 Javascript
使用python编写脚本获取手机当前应用apk的信息
2014/07/21 Python
Python简单删除目录下文件以及文件夹的方法
2015/05/27 Python
Python下实现的RSA加密/解密及签名/验证功能示例
2017/07/17 Python
Python对列表去重的多种方法(四种方法)
2017/12/05 Python
Python SELENIUM上传文件或图片实现过程
2019/10/28 Python
Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法实例分析
2019/12/26 Python
PyQt5 如何让界面和逻辑分离的方法
2020/03/24 Python
基于nexus3配置Python仓库过程详解
2020/06/15 Python
python属于软件吗
2020/06/18 Python
CSS3用@font-face实现自定义英文字体
2013/09/23 HTML / CSS
德国购买健身器材:AsVIVA
2017/08/09 全球购物
英国电视和家用电器购物网站:rlrdistribution.co.uk
2018/11/20 全球购物
船舶专业个人求职信范文
2014/01/02 职场文书
九年级科学教学反思
2014/01/29 职场文书
公司活动方案范文
2014/03/06 职场文书
cf收人广告词
2014/03/14 职场文书
爱牙日活动总结
2014/08/29 职场文书
优秀团员个人总结
2015/02/26 职场文书
2015秋季小学开学寄语
2015/05/27 职场文书
家长对学校的意见和建议
2015/06/03 职场文书
暑期家教宣传单
2015/07/14 职场文书
学校隐患排查制度
2015/08/05 职场文书
小学校本教研总结
2015/08/13 职场文书
2016年艾滋病宣传活动总结
2016/04/01 职场文书