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

你可能感兴趣的文章
postman启动vcruntime140_1.dll未找到解决办法
查看>>
Postman和JMeter怎么选?区别都你总结出来了
查看>>
Postman和Jmeter的区别
查看>>
Postman如何做接口测试:如何导入 swagger 接口文档
查看>>
Postman如何做接口测试:如何导入 swagger 接口文档
查看>>
Qlik助力新西兰最大私人医院提高病患护理水平
查看>>
Postman如何生成接口文档
查看>>
Postman学习之常用断言
查看>>
postman导入curl内容
查看>>
postman居然是用electron开发的,我们来认识下这个框架吧
查看>>
postman常用公共函数
查看>>
Postman常见问题及解决方法
查看>>
PostMan怎样携带登录信息请求后台接口防止出现无法访问资源问题
查看>>
Postman接口传参案例
查看>>
postman接口功能测试
查看>>
Postman接口测试
查看>>
Postman接口测试
查看>>
Postman接口测试/接口自动化实战教程
查看>>
Postman接口测试之POST、GET请求方法
查看>>
Postman接口测试之Post、Get请求方法
查看>>