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爬虫获取多页天涯帖子
Feb 23 Python
python获取代理IP的实例分享
May 07 Python
Python根据指定日期计算后n天,前n天是哪一天的方法
May 29 Python
TensorFlow Session会话控制&amp;Variable变量详解
Jul 30 Python
如何使用django的MTV开发模式返回一个网页
Jul 22 Python
python 字典访问的三种方法小结
Dec 05 Python
Python实现序列化及csv文件读取
Jan 19 Python
Python单元测试模块doctest的具体使用
Feb 10 Python
Python生成器常见问题及解决方案
Mar 21 Python
python使用信号量动态更新配置文件的操作
Apr 01 Python
opencv 图像加法与图像融合的实现代码
Jul 08 Python
Python如何实现Paramiko的二次封装
Jan 30 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
德生PL450的电路分析和低放电路的改进办法
2021/03/02 无线电
阿拉伯的咖啡与水烟
2021/03/03 咖啡文化
PHP 年龄计算函数(精确到天)
2012/06/07 PHP
php使用curl发送json格式数据实例
2013/12/17 PHP
PHP学习笔记(一) 简单了解PHP
2014/08/04 PHP
使用Microsoft Ajax Minifier减小JavaScript文件大小的方法
2010/04/01 Javascript
Js控制弹窗实现在任意分辨率下居中显示
2013/08/01 Javascript
Jquery chosen动态设置值实例介绍
2013/08/08 Javascript
jquery获取颜色在ie和ff下的区别示例介绍
2014/03/28 Javascript
影响jQuery使用的14个方面
2014/09/01 Javascript
详解JavaScript中的forEach()方法的使用
2015/06/08 Javascript
JS实现带提示的星级评分效果完整实例
2015/10/30 Javascript
jQuery入门之层次选择器实例简析
2015/12/11 Javascript
三种Node.js写文件的方式
2016/03/08 Javascript
Javascript中的对象和原型(二)
2016/08/12 Javascript
浅析Vue实例以及生命周期
2018/08/14 Javascript
Angular6 用户自定义标签开发的实现方法
2019/01/08 Javascript
详解在Javascript中进行面向切面编程
2019/04/28 Javascript
使用vue实现一个电子签名组件的示例代码
2020/01/06 Javascript
nuxt 页面路由配置,主页轮播组件开发操作
2020/11/05 Javascript
[01:45]DOTA2新英雄“神谕者”全方位展示
2014/11/21 DOTA
Python实现读写sqlite3数据库并将统计数据写入Excel的方法示例
2017/08/07 Python
Python利用Scrapy框架爬取豆瓣电影示例
2020/01/17 Python
flask框架自定义url转换器操作详解
2020/01/25 Python
解决pytorch 交叉熵损失输出为负数的问题
2020/07/07 Python
html5实现图片转圈的动画效果——让页面动起来
2017/10/16 HTML / CSS
墨西哥网上购物:Linio墨西哥
2016/10/20 全球购物
来自世界各地的饮料:Flavourly
2019/05/06 全球购物
华为慧通笔试题
2016/04/22 面试题
物流专业大学生求职信范文
2013/10/28 职场文书
幼儿园园长岗位职责
2013/11/26 职场文书
学年自我鉴定
2014/01/16 职场文书
2014民事授权委托书范本
2014/09/29 职场文书
大学四年个人总结
2015/03/03 职场文书
如何用python反转图片,视频
2021/04/24 Python
python爬取网页版QQ空间,生成各类图表
2021/06/02 Python