Calculating MD5 Hash for File Integrity

  • Share this:

Code introduction


This function calculates the MD5 hash of a specified file, which is commonly used to verify the integrity of files.


Technology Stack : hashlib

Code Type : File hash calculation

Code Difficulty : Intermediate


                
                    
import csv
import hashlib
import json
import os
import re
import sys
import time

def calculate_hash(file_path):
    """计算文件的哈希值,使用MD5算法

    Args:
        file_path (str): 文件的路径

    Returns:
        str: 文件的MD5哈希值
    """
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()                
              
Tags: