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脚本实现网卡流量监控
Feb 14 Python
django反向解析和正向解析的方式
Jun 05 Python
python3正则提取字符串里的中文实例
Jan 31 Python
Django框架实现的普通登录案例【使用POST方法】
May 15 Python
Python转换时间的图文方法
Jul 01 Python
详解python实现数据归一化处理的方式:(0,1)标准化
Jul 17 Python
浅谈python中统计计数的几种方法和Counter详解
Nov 07 Python
Django 批量插入数据的实现方法
Jan 12 Python
深入浅析Python代码规范性检测
Jul 31 Python
Python下载网易云歌单歌曲的示例代码
Aug 12 Python
python 实现图与图之间的间距调整subplots_adjust
May 21 Python
Pytorch中的数据集划分&正则化方法
May 27 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 FPDF类库应用实现代码
2009/03/20 PHP
php+mysql不用递归实现的无限级分类实例(非递归)
2014/07/08 PHP
PHP实现的sqlite数据库连接类
2014/12/12 PHP
PHP判断数组是否为空的常用方法(五种方法)
2017/02/08 PHP
javascript 页面只自动刷新一次
2009/07/10 Javascript
使用Firebug对js进行断点调试的图文方法
2011/04/02 Javascript
javascript模拟枚举的简单实例
2014/03/06 Javascript
jQuery如何将选中的对象转化为原始的DOM对象
2014/06/09 Javascript
jquery实现图片上传之前预览的方法
2015/07/11 Javascript
如何判断Javascript对象是否存在的简单实例
2016/05/18 Javascript
JS生成不重复的随机数组的简单实例
2016/07/10 Javascript
Vue自定义指令介绍(2)
2016/12/08 Javascript
JS常见疑难点分析之match,charAt,charCodeAt,map,search用法分析
2016/12/25 Javascript
解决vue 更改计算属性后select选中值不更改的问题
2018/03/02 Javascript
微信小程序之批量上传并压缩图片的实例代码
2018/07/05 Javascript
解决node-sass偶尔安装失败的方法小结
2018/12/05 Javascript
Bootstarp在pycharm中的安装及简单的使用方法
2019/04/19 Javascript
layui问题之模拟table表格中的选中按钮选中事件的方法
2019/09/20 Javascript
详解JavaScript中分解数字的三种方法
2021/01/05 Javascript
javascript实现倒计时关闭广告
2021/02/09 Javascript
django的模型类管理器——数据库操作的封装详解
2020/04/01 Python
如何基于python对接钉钉并获取access_token
2020/04/21 Python
利用pandas向一个csv文件追加写入数据的实现示例
2020/04/23 Python
sklearn线性逻辑回归和非线性逻辑回归的实现
2020/06/09 Python
欧舒丹比利时官网:L’OCCITANE比利时
2017/04/25 全球购物
高中生学习总结的自我评价范文
2013/10/13 职场文书
战友聚会邀请函
2014/01/18 职场文书
2014基层党员干部学习全国两会心得体会
2014/03/17 职场文书
《画杨桃》教学反思
2014/04/13 职场文书
校园文明倡议书
2014/05/16 职场文书
农村文化活动总结
2014/08/28 职场文书
寒暑假实习证明书模板
2014/11/29 职场文书
高中同学会致辞
2015/08/01 职场文书
2019年大学推荐信
2019/06/24 职场文书
MySQL基础(二)
2021/04/05 MySQL
python区块链持久化和命令行接口实现简版
2022/05/25 Python