Python Program - Find Hash of File

www.igi‮f‬tidea.com

Here's a Python program that calculates the hash of a file:

import hashlib

def calculate_file_hash(filename):
    """
    Calculates the hash of a file.

    Args:
        filename: The path of the file to calculate the hash for.

    Returns:
        The hash of the file.
    """
    hash_object = hashlib.sha256()

    with open(filename, "rb") as f:
        # Read the file in chunks to avoid loading the whole file into memory
        for chunk in iter(lambda: f.read(4096), b""):
            hash_object.update(chunk)

    return hash_object.hexdigest()

# Example usage:
filename = "example.txt"
file_hash = calculate_file_hash(filename)
print(file_hash) # Output: a3a8c3f919eeaae1e01b0cdedf2d2baa2f52deef13c150b287265c8f1329f7d1

In this program, we define a function called calculate_file_hash() that takes a filename as its argument, and returns the hash of the file.

Inside the function, we first create a hashlib.sha256() object to compute the hash. We then open the file in binary mode using the open() function, and read it in chunks using the read() method. We update the hash object with each chunk using the update() method.

Finally, we return the hexadecimal representation of the hash using the hexdigest() method.

In the example usage, we calculate the hash of a file called example.txt using the calculate_file_hash() function, and print it out using the print() function.