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

你可能感兴趣的文章
percona-xtrabackup 备份
查看>>
SpringBoot集成OpenOffice实现doc文档转html
查看>>
ROS中机器人的强化学习路径规划器
查看>>
perl---2012学习笔记
查看>>
Perl6 必应抓取(1):测试版代码
查看>>
Perl的基本語法
查看>>
perl输出中文有乱码
查看>>
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password). 大数据ssh权限问题 hadoop起不来 hadoopssh错
查看>>
PermissionError:Python 中的 [Errno 13]
查看>>
PermissionError:[Errno 13] 权限被拒绝:‘/manage.py‘
查看>>
Permutation
查看>>
PE文件,节头有感IMAGE_SECTION_HEADER
查看>>
PE查找文件偏移地址
查看>>
PE知识复习之PE的导入表
查看>>
PFX(Parallel Framework) and Traditional Multithreading
查看>>
PGOS:今天动手给电脑装青苹果Win7 X64位系统
查看>>
pgpool-II3.1 的内存泄漏(一)
查看>>
PgSQL · 特性分析 · PG主备流复制机制
查看>>
PGSQL主键序列
查看>>
PGSQL安装PostGIS扩展模块
查看>>