博客
关于我
Python实现检测文件的MD5值来查找重复文件
阅读量:260 次
发布时间:2019-03-01

本文共 1686 字,大约阅读时间需要 5 分钟。

为了简化检测作弊行为,开发者提出了利用MD5值的方法。虽然这种方法对抄袭行为的检测作用有限,但仍然具有一定的防范意义。为了实现这一目标,开发了两种MD5计算方式。

第一种方法是通过Python脚本直接读取文件内容并计算MD5值。该方法的核心代码如下:

import hashlibimport osdef get_md5_01(file_path):    md5 = None    if os.path.isfile(file_path):        with open(file_path, 'rb') as f:            md5_obj = hashlib.md5()            md5_obj.update(f.read())            hash_code = md5_obj.hexdigest()            f.close()            md5 = str(hash_code).lower()    return md5

第二种方法则采用了分块读取的方式,适用于处理较大的文件。其代码如下:

import hashlibimport osfrom collections import Counterdef get_md5_02(file_path):    md5_obj = hashlib.md5()    with open(file_path, 'rb') as f:        while True:            chunk = f.read(8096)            if not chunk:                break            md5_obj.update(chunk)    hash_code = md5_obj.hexdigest()    return str(hash_code).lower()

为了实现文件批量检测,开发者编写了一个脚本。该脚本的主要功能是遍历指定目录下的所有文件,计算每个文件的MD5值,并记录存在重复MD5值的文件路径。

脚本代码如下:

import hashlibimport osfrom collections import Counterdef main():    output_path = os.getcwd()    output_list = []    for path, dir_list, file_list in os.walk(output_path):        for file_name in file_list:            file_path = os.path.join(path, file_name)            output_list.append(file_path)        md5_list = [get_md5_01(file_path) for file_path in output_list]    duplicate_count = Counter(md5_list)        for md5, count in duplicate_count.items():        if count > 1:            duplicate_indices = [i for i, value in enumerate(md5_list) if value == md5]            print(f"MD5值重复:{md5}")            for index in duplicate_indices:                file_path = output_list[index]                print(f"文件路径:{file_path}")

通过上述方法,用户可以轻松检测文件是否存在重复MD5值,进而发现可能的作弊行为。

转载地址:http://yxmx.baihongyu.com/

你可能感兴趣的文章
quagga 和 zebos
查看>>
poj 1286 Necklace of Beads
查看>>
POJ 1321 棋盘问题
查看>>
poj 1321(回溯)
查看>>
Qt高级——Qt元对象系统源码解析
查看>>
qt调用vs2008编写的dll动态库(隐式调用)
查看>>
Qt读取注册表默认值
查看>>
poj 1679 判断MST是不是唯一的 (次小生成树)
查看>>
POJ 1703 Find them, Catch them
查看>>
POJ 1703 Find them, Catch them 并查集
查看>>
POJ 1738 An old Stone Game(石子合并)
查看>>
POJ 1740 A New Stone Game(博弈)题解
查看>>
Qt网络编程之实例二POST方式
查看>>
POJ 1765 November Rain
查看>>
poj 1860 Currency Exchange
查看>>
POJ 1961 Period
查看>>
POJ 2019 Cornfields (二维RMQ)
查看>>
poj 2057 The Lost House 贪心思想在动态规划上的应用
查看>>
poj 2057 树形DP,数学期望
查看>>
poj 2112 最优挤奶方案
查看>>