Calculating File Hash Value

  • Share this:

Code introduction


This function calculates the hash value of the specified file, which is usually used to verify the consistency of the file.


Technology Stack : csv, hashlib, json, os, re, sys

Code Type : File hash calculation

Code Difficulty : Intermediate


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

def hash_file(file_path):
    """计算文件内容的哈希值。

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

    Returns:
        str: 文件的哈希值。
    """
    hasher = hashlib.sha256()
    with open(file_path, 'rb') as file:
        buf = file.read()
        hasher.update(buf)
    return hasher.hexdigest()