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

yipeiwu_com6年前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中传递参数到URLconf的视图函数中的方法

有时你会发现你写的视图函数是十分类似的,只有一点点的不同。 比如说,你有两个视图,它们的内容是一致的,除了它们所用的模板不太一样: # urls.py from django.co...

python 编码规范整理

一 代码编排 1 缩进4个空格的缩进(编辑器都可以完成此功能),不要使用Tap,更不能混合使用Tap和空格。 2 每行最大长度79,换行可以使用反斜杠,最好使用圆括号。换行点要在操作符的...

Python实现的tab文件操作类分享

类代码: # -*- coding:gbk -*- import os class TABFILE: def __init__(self, filename, dest_fi...

python多进程重复加载的解决方式

flask多进程会引起重复加载, 解决方法:把耗资源的加载挪到函数里面或者类里面,就不会重复加载资源了。 测试发现,不是flask引起的,是多进程会引起重复加载python文件。 把fl...

python扫描proxy并获取可用代理ip的实例

今天咱写一个挺实用的工具,就是扫描并获取可用的proxy 首先呢,我先百度找了一个网站:http://www.xicidaili.com 作为例子 这个网站里公布了许多的国内外可用的代理...