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算法之栈(stack)的实现
Aug 18 Python
python实现简单ftp客户端的方法
Jun 28 Python
Python实现的RSS阅读器实例
Jul 25 Python
在Linux系统上部署Apache+Python+Django+MySQL环境
Dec 24 Python
详解python中xlrd包的安装与处理Excel表格
Dec 16 Python
python+opencv实现的简单人脸识别代码示例
Nov 14 Python
python爬虫获取小区经纬度以及结构化地址
Dec 30 Python
python爬虫基础教程:requests库(二)代码实例
Apr 09 Python
Tensorflow轻松实现XOR运算的方式
Feb 03 Python
Python单链表原理与实现方法详解
Feb 22 Python
自定义实现 PyQt5 下拉复选框 ComboCheckBox的完整代码
Mar 30 Python
python 比较字典value的最大值的几种方法
Apr 17 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显示MySQL数据的三种方法
2008/06/05 PHP
php使用ZipArchive提示Fatal error: Class ZipArchive not found in的解决方法
2014/11/04 PHP
Thinkphp5 微信公众号token验证不成功的原因及解决方法
2017/11/12 PHP
使用Zookeeper分布式部署PHP应用程序
2019/03/15 PHP
jquery创建div 实现代码
2009/04/27 Javascript
查看源码的工具 学习jQuery源码不错的工具
2011/12/26 Javascript
jQuery 瀑布流 绝对定位布局(二)(延迟AJAX加载图片)
2012/05/23 Javascript
js鼠标滑过弹出层的定位IE6bug解决办法
2012/12/26 Javascript
JavaScript bold方法入门实例(把指定文字显示为粗体)
2014/10/17 Javascript
JQuery CheckBox(复选框)操作方法汇总
2015/04/15 Javascript
jQuery的end()方法使用详解
2015/07/15 Javascript
什么是JavaScript中的结果值?
2016/10/08 Javascript
vue组件学习教程
2017/09/09 Javascript
JavaScript使用indexOf()实现数组去重的方法分析
2018/09/04 Javascript
微信小程序云开发实现数据添加、查询和分页
2019/05/17 Javascript
微信小程序用户授权弹窗 拒绝时引导用户重新授权实现
2019/07/29 Javascript
vue中使用elementUI组件手动上传图片功能
2019/12/13 Javascript
vue 解决setTimeOut和setInterval函数无效报错的问题
2020/07/30 Javascript
JS实现简单贪吃蛇小游戏
2020/10/28 Javascript
python实现代码行数统计示例分享
2014/02/10 Python
使用Python的Twisted框架构建非阻塞下载程序的实例教程
2016/05/25 Python
python使用os.listdir和os.walk获得文件的路径的方法
2017/12/16 Python
Python 新建文件夹与复制文件夹内所有内容的方法
2018/10/27 Python
python实现QQ空间自动点赞功能
2019/04/09 Python
python pandas时序处理相关功能详解
2019/07/03 Python
python读出当前时间精度到秒的代码
2019/07/05 Python
python爬虫之遍历单个域名
2019/11/20 Python
python解析多层json操作示例
2019/12/30 Python
python GUI库图形界面开发之PyQt5不规则窗口实现与显示GIF动画的详细方法与实例
2020/03/09 Python
python基本算法之实现归并排序(Merge sort)
2020/09/01 Python
英国音乐设备和乐器商店:Gear4music
2017/10/16 全球购物
五四青年节优秀演讲稿范文
2014/05/28 职场文书
运动会的口号
2014/06/09 职场文书
2015年世界无车日活动总结
2015/03/23 职场文书
斗罗大陆八大特殊魂兽,龙族始祖排榜首,第五最残忍(翠魔鸟)
2022/03/18 国漫