import hashlib
def hash_file_contents(filepath, hash_algorithm='sha256'):
"""
Hashes the contents of a file using the specified algorithm.
Args:
filepath (str): The path to the file.
hash_algorithm (str): The hashing algorithm to use (e.g., 'md5', 'sha1', 'sha256', 'sha512'). Defaults to 'sha256'.
Returns:
str: The hexadecimal representation of the file's hash, or None if the file does not exist or an error occurs.
"""
try:
# Open the file in binary read mode
with open(filepath, 'rb') as f:
# Create a hash object based on the specified algorithm
hasher = hashlib.new(hash_algorithm)
# Read the file in chunks to handle large files efficiently
while True:
chunk = f.read(4096) # Read 4KB chunks
if not chunk:
break
hasher.update(chunk)
# Return the hexadecimal representation of the hash
return hasher.hexdigest()
except FileNotFoundError:
print(f"Error: File not found at {filepath}")
return None
except Exception as e:
print(f"An error occurred: {e}")
return None
if __name__ == '__main__':
# Example usage:
file_path = 'test_file.txt' # Replace with your file path
# Create a dummy file for testing
with open(file_path, 'w') as f:
f.write("This is a test file.\n")
f.write("It contains some text.\n")
# Calculate the SHA256 hash of the file
sha256_hash = hash_file_contents(file_path, 'sha256')
if sha256_hash:
print(f"SHA256 Hash: {sha256_hash}")
# Calculate the MD5 hash of the file
md5_hash = hash_file_contents(file_path, 'md5')
if md5_hash:
print(f"MD5 Hash: {md5_hash}")
Add your comment