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多进程同步Lock、Semaphore、Event实例
Nov 21 Python
python实现自动更换ip的方法
May 05 Python
python制作花瓣网美女图片爬虫
Oct 28 Python
Python 中的with关键字使用详解
Sep 11 Python
Python实现对特定列表进行从小到大排序操作示例
Feb 11 Python
pyqt5 从本地选择图片 并显示在label上的实例
Jun 13 Python
Python爬虫使用浏览器cookies:browsercookie过程解析
Oct 22 Python
Python使用matplotlib 画矩形的三种方式分析
Oct 31 Python
Python破解BiliBili滑块验证码的思路详解(完美避开人机识别)
Feb 17 Python
python3中datetime库,time库以及pandas中的时间函数区别与详解
Apr 16 Python
python爬虫多次请求超时的几种重试方法(6种)
Dec 01 Python
关于探究python中sys.argv时遇到的问题详解
Feb 23 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实现加密的几种方式介绍
2015/02/22 PHP
php实现的redis缓存类定义与使用方法示例
2017/08/09 PHP
thinkPHP框架实现生成条形码的方法示例
2018/06/06 PHP
javascript flash下fromCharCode和charCodeAt方法使用说明
2008/01/12 Javascript
js限制文本框为整数和货币的函数代码
2010/10/13 Javascript
jQuery 图片切换插件(代码比较少)
2012/05/07 Javascript
Jquery中使用setInterval和setTimeout的方法
2013/04/08 Javascript
jQuery.lazyload+masonry改良图片瀑布流代码
2014/06/20 Javascript
jquery实现手风琴效果
2015/11/20 Javascript
概述jQuery的元素筛选
2016/11/23 Javascript
微信小程序 本地存储及登录页面处理实例详解
2017/01/11 Javascript
基于jquery实现左右上下移动效果
2018/05/02 jQuery
vue实现图片预览组件封装与使用
2019/07/13 Javascript
jquery传参及获取方式(两种方式)
2020/02/13 jQuery
JavaScript中break、continue和return的用法区别实例分析
2020/03/02 Javascript
python安装Scrapy图文教程
2017/08/14 Python
python中实现指定时间调用函数示例代码
2017/09/08 Python
python基于ID3思想的决策树
2018/01/03 Python
用tensorflow实现弹性网络回归算法
2018/01/09 Python
Python处理中文标点符号大集合
2018/05/14 Python
将python图片转为二进制文本的实例
2019/01/24 Python
对Python3中dict.keys()转换成list类型的方法详解
2019/02/03 Python
详解python pandas 分组统计的方法
2019/07/30 Python
pytorch 彩色图像转灰度图像实例
2020/01/13 Python
Python实现打包成库供别的模块调用
2020/07/13 Python
matplotlib 画动态图以及plt.ion()和plt.ioff()的使用详解
2021/01/05 Python
canvas实现烟花的示例代码
2020/01/16 HTML / CSS
全球领先的美容用品专卖店:Beauty Plus Salon
2018/09/04 全球购物
Python中pass语句的作用是什么
2016/06/01 面试题
园林技术个人的自我评价
2014/01/08 职场文书
“学雷锋活动月”总结
2014/03/09 职场文书
经典的毕业生自荐信范文
2014/04/14 职场文书
幼儿园教师的自我评价范文
2014/09/17 职场文书
维稳工作承诺书
2015/01/20 职场文书
专家推荐信怎么写
2015/03/25 职场文书
CSS Transition通过改变Height实现展开收起元素
2021/08/07 HTML / CSS