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

你可能感兴趣的文章
PowerDesigner使用教程:给字段添加唯一约束
查看>>
QGIS中怎样设置图层样式并导出地图样式
查看>>
PowerDesigner使用笔记
查看>>
QGIS中怎样实现数据坐标系转换
查看>>
PowerDesigner学习--基本步骤
查看>>
PowerDesigner导出Report通用报表
查看>>
PowerDesigner教程系列(二)概念数据模型
查看>>
Powerdesigner显示表的comment和列的comment的方法
查看>>
PowerDesigner最基础的使用方法入门学习
查看>>
PowerDesigner版本控制器设置权限
查看>>
PowerDesigner生成数据模型并导出报告
查看>>
QGIS中导入dwg文件并使用GetWKT插件获取绘制元素WKT字符串以及QuickWKT插件实现WKT显示在图层
查看>>
PowerDesigner逆向工程从SqlServer数据库生成PDM(图文教程)
查看>>
PowerEdge T630服务器安装机器学习环境(Ubuntu18.04、Nvidia 1080Ti驱动、CUDA及CUDNN安装)
查看>>
PowerPC-object与elf中的符号引用
查看>>
QFileSystemModel
查看>>
Powershell DSC 5.0 - 参数,证书加密账号,以及安装顺序
查看>>
PowerShell 批量签入SharePoint Document Library中的文件
查看>>
Powershell 自定义对象小技巧
查看>>
pytorch从预训练权重加载完全相同的层
查看>>