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 30 Python
在Python中操作列表之list.extend()方法的使用
May 20 Python
Python实现截屏的函数
Jul 26 Python
Using Django with GAE Python 后台抓取多个网站的页面全文
Feb 17 Python
Python数组遍历的简单实现方法小结
Apr 27 Python
Python3解决棋盘覆盖问题的方法示例
Dec 07 Python
spark dataframe 将一列展开,把该列所有值都变成新列的方法
Jan 29 Python
Django REST Framework之频率限制的使用
Sep 29 Python
简单了解python中的f.b.u.r函数
Nov 02 Python
Python GUI编程学习笔记之tkinter控件的介绍及基本使用方法详解
Mar 30 Python
解决PyCharm不在run输出运行结果而不是再Console里输出的问题
Sep 21 Python
python中pyplot基础图标函数整理
Nov 10 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
终于听上了直流胆调频
2021/03/02 无线电
一个用于mysql的数据库抽象层函数库
2006/10/09 PHP
服务器web工具 php环境下
2010/12/29 PHP
php将时间差转换为字符串提示
2011/09/07 PHP
PHP中常用的字符串格式化函数总结
2014/11/19 PHP
CentOS下与Apache连接的PHP多版本共存方案实现详解
2015/12/19 PHP
基于PHP实现简单的随机抽奖小程序
2016/01/05 PHP
PHP调用API接口实现天气查询功能的示例
2017/09/21 PHP
TP5框架使用QueryList采集框架爬小说操作示例
2020/03/26 PHP
不错的JS中变量相关的细节分析
2007/08/13 Javascript
juqery 学习之四 筛选查找
2010/11/30 Javascript
Jquery实现显示和隐藏的4种简单方式
2013/08/28 Javascript
完美解决IE低版本不支持call与apply的问题
2013/12/05 Javascript
用js传递value默认值的示例代码
2014/09/11 Javascript
原生Ajax 和jQuery Ajax的区别示例分析
2014/12/17 Javascript
javascript面向对象之this关键词用法分析
2015/01/13 Javascript
js实现文本框选中的方法
2015/05/26 Javascript
jquery结合html实现中英文页面切换
2016/11/29 Javascript
vue路由事件beforeRouteLeave及组件内定时器的清除方法
2018/09/29 Javascript
vue移动端项目缓存问题实践记录
2018/10/29 Javascript
微信小程序保存多张图片的实现方法
2019/03/05 Javascript
[15:39]教你分分钟做大人:龙骑士
2014/10/30 DOTA
Python按行读取文件的实现方法【小文件和大文件读取】
2016/09/19 Python
Python+matplotlib实现填充螺旋实例
2018/01/15 Python
ubuntu安装mysql pycharm sublime
2018/02/20 Python
在PYQT5中QscrollArea(滚动条)的使用方法
2019/06/14 Python
Win10系统下安装labelme及json文件批量转化方法
2019/07/30 Python
详解BeautifulSoup获取特定标签下内容的方法
2020/12/07 Python
Python扫描端口的实现
2021/01/25 Python
英国Office鞋店德国网站:在线购买鞋子、靴子和运动鞋
2018/12/19 全球购物
请写出char *p与"零值"比较的if语句
2014/09/24 面试题
资产评估专业学生的自我鉴定
2013/11/14 职场文书
学生宿舍管理制度
2014/01/30 职场文书
大学校运会广播稿
2014/02/03 职场文书
酒店节能降耗方案
2014/05/08 职场文书
小学生纪念九一八事变演讲稿
2014/09/14 职场文书