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 相关文章推荐
Django集成百度富文本编辑器uEditor攻略
Jul 04 Python
python实现上传样本到virustotal并查询扫描信息的方法
Oct 05 Python
使用Python编写一个模仿CPU工作的程序
Apr 16 Python
Python根据已知邻接矩阵绘制无向图操作示例
Jun 23 Python
在PyCharm下使用 ipython 交互式编程的方法
Jan 17 Python
Python Django给admin添加Action的方法实例详解
Apr 29 Python
python使用threading.Condition交替打印两个字符
May 07 Python
python修改字典键(key)的方法
Aug 05 Python
完美解决TensorFlow和Keras大数据量内存溢出的问题
Jul 03 Python
详解pandas中利用DataFrame对象的.loc[]、.iloc[]方法抽取数据
Dec 13 Python
pytorch 中nn.Dropout的使用说明
May 20 Python
python中的getter与setter你了解吗
Mar 24 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
怎样在UNIX系统下安装MySQL
2006/10/09 PHP
php实现websocket实时消息推送
2018/03/30 PHP
JQuery在页面中添加和除移DOM示例代码
2013/06/24 Javascript
jquery中插件实现自动添加用户的具体代码
2013/11/15 Javascript
Jquery EasyUI中弹出确认对话框以及加载效果示例代码
2014/02/13 Javascript
Jquery插件分享之气泡形提示控件grumble.js
2014/05/20 Javascript
JavaScript使用push方法添加一个元素到数组末尾用法实例
2015/04/06 Javascript
jQuery中 attr() 方法使用小结
2015/05/03 Javascript
分享我对JS插件开发的一些感想和心得
2016/02/04 Javascript
AngularJS通过$http和服务器通信详解
2016/09/21 Javascript
jquery实现数字输入框
2017/02/22 Javascript
基于Axios 常用的请求方法别名(详解)
2018/03/13 Javascript
JS中数据结构之栈
2019/01/01 Javascript
es6数据变更同步到视图层的方法
2019/03/04 Javascript
基于js判断浏览器是否支持webGL
2020/04/18 Javascript
在elementui中Notification组件添加点击事件实例
2020/11/11 Javascript
Python smtplib实现发送邮件功能
2018/05/22 Python
Python定义函数功能与用法实例详解
2019/04/08 Python
Python将string转换到float的实例方法
2019/07/29 Python
python开头的coding设置方法
2019/08/08 Python
python图形开发GUI库pyqt5的详细使用方法及各控件的属性与方法
2020/02/14 Python
Python基于类路径字符串获取静态属性
2020/03/12 Python
记录模型训练时loss值的变化情况
2020/06/16 Python
Python读取ini配置文件传参的简单示例
2021/01/05 Python
CSS3中border-radius属性设定圆角的使用技巧
2016/05/10 HTML / CSS
localStorage的过期时间设置的方法详解
2018/11/26 HTML / CSS
Yahoo-PHP面试题2
2014/12/06 面试题
酒店执行总经理岗位职责
2013/12/15 职场文书
《三顾茅庐》教学反思
2014/04/10 职场文书
环境卫生标语
2014/06/09 职场文书
图书室标语
2014/06/21 职场文书
思想作风整顿个人剖析材料
2014/10/06 职场文书
2015年初中元旦晚会活动总结
2014/11/28 职场文书
2016幼儿园中班开学寄语
2015/12/03 职场文书
2016年“世界环境日”校园广播稿
2015/12/18 职场文书
golang通过递归遍历生成树状结构的操作
2021/04/28 Golang