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)

相关文章

python numpy 反转 reverse示例

python 的向量反转有一个很简单的办法 # 创建向量 impot numpy as np a = np.array([1,2,3,4,5,6]) b=a[::-1] print(...

低版本中Python除法运算小技巧

首先要说的是python中的除法运算,在python 2.5版本中存在两种除法运算,即所谓的true除法和floor除法。当使用x/y形式进行除法运算时,如果x和y都是整形,那么运算的会...

python实现车牌识别的示例代码

python实现车牌识别的示例代码

某天回家之时,听到有个朋友说起他正在做一个车牌识别的项目 于是对其定位车牌的位置算法颇有兴趣,今日有空得以研究,事实上车牌识别算是比较成熟的技术了, 这里我只是简单实现。 我的思路为:...

python实现定时压缩指定文件夹发送邮件

工作中每天需要收集部门内的FR文件,发送给外部部门的同事帮忙上传,这么发了有大半年,昨天亮光一闪,为什么不做成自动化呢,于是用python实现了整个流程,今天体验了一下真是美滋滋。 代码...

详解Python3中yield生成器的用法

任何使用yield的函数都称之为生成器,如: def count(n): while n > 0: yield n #生成值:n n -= 1...