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是编译运行的验证方法
Jan 30 Python
Python中文分词工具之结巴分词用法实例总结【经典案例】
Apr 15 Python
python中logging库的使用总结
Oct 18 Python
基于Python os模块常用命令介绍
Nov 03 Python
Python实现随机生成手机号及正则验证手机号的方法
Apr 25 Python
对python添加模块路径的三种方法总结
Oct 16 Python
django的ORM模型的实现原理
Mar 04 Python
详解Python 重学requests发起请求的基本方式
Feb 07 Python
TensorFlow的环境配置与安装方法
Feb 20 Python
python利用后缀表达式实现计算器功能
Feb 22 Python
Pytorch反向传播中的细节-计算梯度时的默认累加操作
Jun 05 Python
python ansible自动化运维工具执行流程
Jun 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
全国FM电台频率大全 - 30 宁夏回族自治区
2020/03/11 无线电
PHP中判断文件存在使用is_file还是file_exists?
2015/04/03 PHP
php实现短信发送代码
2015/07/05 PHP
PHP实现图片不变型裁剪及图片按比例裁剪的方法
2016/01/14 PHP
php 运算符与表达式详细介绍
2016/11/30 PHP
php中final关键字用法分析
2016/12/07 PHP
YII2框架中使用yii.js实现的post请求
2017/04/09 PHP
PHP实现时间比较和时间差计算的方法示例
2017/07/24 PHP
php中加密解密DES类的简单使用方法示例
2020/03/26 PHP
JavaScript 实现??打印?理
2007/04/28 Javascript
javascript使用isNaN()函数判断变量是否为数字
2013/09/21 Javascript
js实现右下角提示框的方法
2015/02/03 Javascript
JavaScript中的slice()方法使用详解
2015/06/06 Javascript
基于JavaScript实现Json数据根据某个字段进行排序
2015/11/24 Javascript
AngularJs bootstrap搭载前台框架——准备工作
2016/09/01 Javascript
jQuery实现获取h1-h6标题元素值的方法
2017/03/06 Javascript
Jquery-data的三种用法
2017/04/18 jQuery
vue中子组件调用兄弟组件方法
2018/07/06 Javascript
js实现文件上传功能 后台使用MultipartFile
2018/09/08 Javascript
使用 Jest 和 Supertest 进行接口端点测试实例详解
2020/04/25 Javascript
微信小程序开发(三):返回上一级页面并刷新操作示例【页面栈】
2020/06/01 Javascript
Python中处理时间的几种方法小结
2015/04/09 Python
Python工程师面试题 与Python Web相关
2016/01/14 Python
python使用tensorflow深度学习识别验证码
2018/04/03 Python
python读取csv和txt数据转换成向量的实例
2019/02/12 Python
Python嵌套式数据结构实例浅析
2019/03/05 Python
Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围
2019/06/25 Python
tensorflow之并行读入数据详解
2020/02/05 Python
如何在pycharm中安装第三方包
2020/10/27 Python
德国电子商城:ComputerUniverse
2017/04/21 全球购物
自荐书范文
2013/12/08 职场文书
企业员工培训感言
2014/02/26 职场文书
人身损害赔偿协议书范本
2014/09/27 职场文书
职称评定个人总结
2015/03/05 职场文书
python opencv人脸识别考勤系统的完整源码
2021/04/26 Python
如何更改Win11声音输出设备?Win11声音输出设备四种更改方法
2022/04/08 数码科技