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比较文件夹比另一同名文件夹多出的文件并复制出来的方法
Mar 05 Python
在Python中关于中文编码问题的处理建议
Apr 08 Python
Python赋值语句后逗号的作用分析
Jun 08 Python
Python 40行代码实现人脸识别功能
Apr 02 Python
深入理解python中函数传递参数是值传递还是引用传递
Nov 07 Python
python脚本监控Tomcat服务器的方法
Jul 06 Python
python之super的使用小结
Aug 13 Python
python+splinter自动刷新抢票功能
Sep 25 Python
在Python 中实现图片加框和加字的方法
Jan 26 Python
python os.path.isfile()因参数问题判断错误的解决
Nov 29 Python
pycharm通过ssh连接远程服务器教程
Feb 12 Python
python复合条件下的字典排序
Dec 18 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
ThinkPHP中的create方法与自动令牌验证实例教程
2014/08/22 PHP
PHP5.3以上版本安装ZendOptimizer扩展
2015/03/27 PHP
PHP针对伪静态的注入总结【附asp与Python相关代码】
2017/08/01 PHP
Laravel框架实现修改登录和注册接口数据返回格式的方法
2018/08/17 PHP
Laravel监听数据库访问,打印SQL的例子
2019/10/24 PHP
激活 ActiveX 控件
2006/10/09 Javascript
js模拟hashtable的简单实例
2014/03/06 Javascript
基于JavaScript代码实现pc与手机之间的跳转
2015/12/23 Javascript
在Html中使用Requirejs进行模块化开发实例详解
2016/04/15 Javascript
jquery-mobile表单的创建方法详解
2016/11/23 Javascript
JS中微信小程序自定义底部弹出框
2016/12/22 Javascript
JS如何判断浏览器类型和详细区分IE各版本浏览器
2017/03/04 Javascript
nodejs学习笔记之路由
2017/03/27 NodeJs
vue.js组件vue-waterfall-easy实现瀑布流效果
2017/08/22 Javascript
对于js垃圾回收机制的理解
2017/09/14 Javascript
vue cli升级webapck4总结
2018/04/04 Javascript
Vue实现点击时间获取时间段查询功能
2020/08/21 Javascript
还不懂递归?读完这篇文章保证你会懂
2018/07/29 Javascript
Windows中安装使用Virtualenv来创建独立Python环境
2016/05/31 Python
详解Python 数据库的Connection、Cursor两大对象
2018/06/25 Python
python数据类型之间怎么转换技巧分享
2019/08/20 Python
python扫描线填充算法详解
2020/02/19 Python
用python按照图像灰度值统计并筛选图片的操作(PIL,shutil,os)
2020/06/04 Python
Python之多进程与多线程的使用
2021/02/23 Python
爱游人:Travelliker
2017/09/05 全球购物
Java中的异常处理机制的简单原理和应用
2013/04/27 面试题
建筑工地门卫岗位职责
2014/04/30 职场文书
物业管理专业自荐信
2014/07/01 职场文书
金融专业求职信
2014/08/05 职场文书
领导班子奢靡之风查摆问题及整改措施
2014/09/27 职场文书
成都人事代理协议书
2014/10/25 职场文书
学习走群众路线心得体会
2014/11/05 职场文书
小马王观后感
2015/06/11 职场文书
居安思危观后感
2015/06/11 职场文书
Python入门之使用pandas分析excel数据
2021/05/12 Python
JavaScript中时间格式化新思路toLocaleString()
2021/11/07 Javascript