Python中使用md5sum检查目录中相同文件代码分享

yipeiwu_com5年前Python基础

复制代码 代码如下:

"""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)

相关文章

Django查找网站项目根目录和对正则表达式的支持

Django查找网站项目根目录和对正则表达式的支持

如果你想通过http://127.0.0.1:8000/看网站根目录你将看到一个404错误消息。Django不会增加任何东西在网站根目录,在任何情况下这个URL都不是特殊的 就像在URL...

django 通过ajax完成邮箱用户注册、激活账号的方法

一、图片验证码 django-simple-captcha配置 1.在pycharm中,File====》Settings====》Project:项目名====》Project Int...

python实现用户管理系统

本文实例为大家分享了python实现用户管理系统的具体代码,供大家参考,具体内容如下 《python核心编程》第七章练习题第五题 一、题目描述  userpw2.py。下面的...

Python代码太长换行的实现

末尾加 \ 或 Enter ,回车使用看情况,\通用。 如果是print字符串换行,可以加三个单引号或三个双引号,但是这样回车换行会保留,若要呈现无换行的字符串,引号中每行末尾可加 \...

python调用摄像头拍摄数据集

之前需要做一些目标检测的训练,需要自己采集一些数据集,写了一个小demo来实现图片的采集 使用方法: 指定name的名称,name为分类的标签 按n键拍摄图片 程序会在当前...