Skip to content

Utils

Utils

This module provides utilities for hashing files.

Functions:

Name Description
get_hash

Path) -> str: Calculates and returns the SHA-256 hash of the specified file.

get_hash(path)

Get the hash of a file.

This method opens the specified file in binary mode and calculates the SHA-256 hash by traversing the file inblocks of 4096 bytes. The hash is updated at each iteration to include the contents of the processed block.

Once the entire file has been processed, the method returns the SHA-256 hash value in hexadecimal format.

Note: This method is intended for internal use by the specific code and must not be called directly from other parts of the code.

Parameters:

Name Type Description Default
path Path

Path to the file.

required

Returns:

Name Type Description
str str

Hash of the file.

Source code in pydfirram/core/utils.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def get_hash(path: Path) -> str:
    """
    Get the hash of a file.

    This method opens the specified file in binary mode and calculates the
    SHA-256 hash by traversing the file inblocks of 4096 bytes. The hash is
    updated at each iteration to include the contents of the processed block.

    Once the entire file has been processed, the method returns the SHA-256
    hash value in hexadecimal format.

    Note: This method is intended for internal use by the specific code and
    must not be called directly from other parts of the code.

    Args:
        path (Path): Path to the file.

    Returns:
        str: Hash of the file.
    """
    with open(path, "rb") as f:
        hash_obj = hashlib.sha256()
        for chunk in iter(lambda: f.read(4096), b""):
            hash_obj.update(chunk)
        return hash_obj.hexdigest()