博客
关于我
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/

你可能感兴趣的文章
Objective-C实现基于文件流拷贝文件(附完整源码)
查看>>
Objective-C实现基于模板的双向链表(附完整源码)
查看>>
Objective-C实现基于模板的顺序表(附完整源码)
查看>>
Objective-C实现基本二叉树算法(附完整源码)
查看>>
Objective-C实现堆排序(附完整源码)
查看>>
Objective-C实现填充环形矩阵(附完整源码)
查看>>
Objective-C实现声音录制播放程序(附完整源码)
查看>>
Objective-C实现备忘录模式(附完整源码)
查看>>
Objective-C实现复制粘贴文本功能(附完整源码)
查看>>
Objective-C实现复数类+-x%(附完整源码)
查看>>
Objective-C实现外观模式(附完整源码)
查看>>
Objective-C实现多启发式a star A*算法(附完整源码)
查看>>
Objective-C实现多尺度MSR算法(附完整源码)
查看>>
Objective-C实现多种方法求解定积分(附完整源码)
查看>>
Objective-C实现多组输入(附完整源码)
查看>>
Objective-C实现多项式函数在某个点的评估算法(附完整源码)
查看>>
Objective-C实现多项式哈希算法(附完整源码)
查看>>
Objective-C实现大位数乘法(附完整源码)
查看>>
Objective-C实现大根堆(附完整源码)
查看>>
Objective-C实现奇偶检验码(附完整源码)
查看>>