Python中使用md5sum检查目录中相同文件代码分享


Posted in Python onFebruary 02, 2015
"""This module contains code from

Think Python by Allen B. Downey
http://thinkpython.com
Copyright 2012 Allen B. Downey

License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import os
def walk(dirname):

    """Finds the names of all files in dirname and its subdirectories.
    dirname: string name of directory

    """

    names = []

    for name in os.listdir(dirname):

        path = os.path.join(dirname, name)
        if os.path.isfile(path):

            names.append(path)

        else:

            names.extend(walk(path))

    return names


def compute_checksum(filename):

    """Computes the MD5 checksum of the contents of a file.
    filename: string

    """

    cmd = 'md5sum ' + filename

    return pipe(cmd)


def check_diff(name1, name2):

    """Computes the difference between the contents of two files.
    name1, name2: string filenames

    """

    cmd = 'diff %s %s' % (name1, name2)

    return pipe(cmd)


def pipe(cmd):

    """Runs a command in a subprocess.
    cmd: string Unix command
    Returns (res, stat), the output of the subprocess and the exit status.

    """

    fp = os.popen(cmd)

    res = fp.read()

    stat = fp.close()

    assert stat is None

    return res, stat


def compute_checksums(dirname, suffix):

    """Computes checksums for all files with the given suffix.
    dirname: string name of directory to search

    suffix: string suffix to match
    Returns: map from checksum to list of files with that checksum

    """

    names = walk(dirname)
    d = {}

    for name in names:

        if name.endswith(suffix):

            res, stat = compute_checksum(name)

            checksum, _ = res.split()
            if checksum in d:

                d[checksum].append(name)

            else:

                d[checksum] = [name]
    return d


def check_pairs(names):

    """Checks whether any in a list of files differs from the others.
    names: list of string filenames

    """

    for name1 in names:

        for name2 in names:

            if name1 < name2:

                res, stat = check_diff(name1, name2)

                if res:

                    return False

    return True


def print_duplicates(d):

    """Checks for duplicate files.
    Reports any files with the same checksum and checks whether they

    are, in fact, identical.
    d: map from checksum to list of files with that checksum

    """

    for key, names in d.iteritems():

        if len(names) > 1:

            print 'The following files have the same checksum:'

            for name in names:

                print name
            if check_pairs(names):

                print 'And they are identical.'


if __name__ == '__main__':

    d = compute_checksums(dirname='.', suffix='.py')

    print_duplicates(d)
Python 相关文章推荐
用Python抢过年的火车票附源码
Dec 07 Python
python生成tensorflow输入输出的图像格式的方法
Feb 12 Python
python如何使用unittest测试接口
Apr 04 Python
numpy和pandas中数组的合并、拉直和重塑实例
Jun 28 Python
Python 3 实现定义跨模块的全局变量和使用教程
Jul 07 Python
Django REST framework 视图和路由详解
Jul 19 Python
Python3使用xml.dom.minidom和xml.etree模块儿解析xml文件封装函数的方法
Sep 23 Python
使用Python实现分别输出每个数组
Dec 06 Python
解决pyPdf和pyPdf2在合并pdf时出现异常的问题
Apr 03 Python
Python实现进度条和时间预估的示例代码
Jun 02 Python
PyQt 如何创建自定义QWidget
Mar 24 Python
关于Python中进度条的六个实用技巧分享
Apr 05 Python
Python列表append和+的区别浅析
Feb 02 #Python
Python中的tuple元组详细介绍
Feb 02 #Python
Linux下编译安装MySQL-Python教程
Feb 02 #Python
Python写的服务监控程序实例
Jan 31 #Python
用python 制作图片转pdf工具
Jan 30 #Python
Python是编译运行的验证方法
Jan 30 #Python
Python的类实例属性访问规则探讨
Jan 30 #Python
You might like
PHP的栏目导航程序
2006/10/09 PHP
解析php中反射的应用
2013/06/18 PHP
Fatal error: session_start(): Failed to initialize storage module: files问题解决方法
2014/05/04 PHP
javascript 触发事件列表 比较不错
2009/09/03 Javascript
jQuery 事件队列调整方法
2009/09/18 Javascript
multiSteps 基于Jquery的多步骤滑动切换插件
2011/07/22 Javascript
JS命名空间的另一种实现
2013/08/09 Javascript
js的隐含参数(arguments,callee,caller)使用方法
2014/01/28 Javascript
javaScript 页面自动加载事件详解
2014/02/10 Javascript
分享纯手写漂亮的表单验证
2015/11/19 Javascript
js操作DOM--添加、删除节点的简单实例
2016/07/08 Javascript
Google 地图叠加层实例讲解
2016/08/06 Javascript
JavaScript ES6中export、import与export default的用法和区别
2017/03/14 Javascript
原生js轮播特效
2017/05/18 Javascript
实现一个完整的Node.js RESTful API的示例
2017/09/29 Javascript
vue 使用自定义指令实现表单校验的方法
2018/08/28 Javascript
vue使用canvas实现移动端手写签名
2020/09/22 Javascript
[01:14]英雄,所敬略同——2018完美盛典宣传视频
2018/12/05 DOTA
python实现windows下文件备份脚本
2018/05/27 Python
python批量修改文件编码格式的方法
2018/05/31 Python
transform python环境快速配置方法
2018/09/27 Python
Python Pickle 实现在同一个文件中序列化多个对象
2019/12/30 Python
Python环境管理virtualenv&amp;virtualenvwrapper的配置详解
2020/07/01 Python
德国体育用品网上商店:SC24.com
2016/08/01 全球购物
Made in Design德国:设计师家具、灯具和装饰
2019/10/31 全球购物
微软马来西亚官方网站:Microsoft马来西亚
2019/11/22 全球购物
汉语专业应届生求职信
2013/10/01 职场文书
资产经营总监岗位职责范文
2013/12/01 职场文书
运动会广播稿400字
2014/01/25 职场文书
城市规划应届毕业生自荐信
2014/07/04 职场文书
房产协议书范本
2014/10/18 职场文书
校长师德表现自我评价
2015/03/04 职场文书
幼儿园教研工作总结2015
2015/05/12 职场文书
2016入党积极分子考察评语
2015/12/01 职场文书
学习心得体会
2019/06/20 职场文书
2019年励志签名:致拼搏路上的自己
2019/10/11 职场文书