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开发WebService系列教程之REST,web.py,eurasia,Django
Jun 30 Python
Python向日志输出中添加上下文信息
May 24 Python
深入学习Python中的上下文管理器与else块
Aug 27 Python
用Python写脚本,实现完全备份和增量备份的示例
Apr 29 Python
Python 2/3下处理cjk编码的zip文件的方法
Apr 26 Python
Python assert语句的简单使用示例
Jul 28 Python
django自带调试服务器的使用详解
Aug 29 Python
Python3.7 读取 mp3 音频文件生成波形图效果
Nov 05 Python
使用Tensorflow将自己的数据分割成batch训练实例
Jan 20 Python
Python dict和defaultdict使用实例解析
Mar 12 Python
python学生管理系统的实现
Apr 05 Python
用python按照图像灰度值统计并筛选图片的操作(PIL,shutil,os)
Jun 04 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为php增加openssl模块的方法
2011/06/14 PHP
mac下Apache + MySql + PHP搭建网站开发环境
2014/06/02 PHP
php第一次无法获取cookie问题处理
2014/12/15 PHP
utf8的编码算法 转载
2006/12/27 Javascript
asp.net和asp下ACCESS的参数化查询
2008/06/11 Javascript
AJAX的跨域与JSONP(为文章自动添加短址的功能)
2010/01/17 Javascript
javascript相等运算符与等同运算符详细介绍
2013/11/09 Javascript
基于jquery实现放大镜效果
2015/08/17 Javascript
javascript实现tab切换特效
2015/11/12 Javascript
javascript时间排序算法实现活动秒杀倒计时效果
2021/01/28 Javascript
vue 指定组件缓存实例详解
2018/04/01 Javascript
swiper.js插件实现pc端文本上下滑动功能示例
2018/12/03 Javascript
关于element-ui的隐藏组件el-scrollbar的使用
2019/05/29 Javascript
OpenLayers3实现测量功能
2020/09/25 Javascript
[01:35]辉夜杯战队访谈宣传片—iG.V
2015/12/25 DOTA
[01:06:54]DOTA2-DPC中国联赛 正赛 RNG vs Dragon BO3 第一场 1月24日
2021/03/11 DOTA
python 中的列表解析和生成表达式
2011/03/10 Python
Python yield 小结和实例
2014/04/25 Python
进一步探究Python中的正则表达式
2015/04/28 Python
python获取多线程及子线程的返回值
2017/11/15 Python
python面试题之列表声明实例分析
2019/07/08 Python
解决python多行注释引发缩进错误的问题
2019/08/23 Python
Python如何基于rsa模块实现非对称加密与解密
2020/01/03 Python
python 实现仿微信聊天时间格式化显示的代码
2020/04/17 Python
Pytorch之Tensor和Numpy之间的转换的实现方法
2020/09/03 Python
个人简历自我评价
2014/02/02 职场文书
大专毕业自我鉴定
2014/02/04 职场文书
金融学专科生自我鉴定
2014/02/21 职场文书
仓库管理计划书
2014/05/04 职场文书
商铺消防安全责任书
2014/07/29 职场文书
2015年七七事变78周年纪念活动方案
2015/05/06 职场文书
2015年领导班子工作总结
2015/05/23 职场文书
搞笑婚礼主持词开场白
2015/11/24 职场文书
Python opencv缺陷检测的实现及问题解决
2021/04/24 Python
Redis集群新增、删除节点以及动态增加内存的方法
2021/09/04 Redis
海贼王十大潜力果实,路飞仅排第十,第一可毁世界(震震果实)
2022/03/18 日漫