1. import hashlib
  2. def hash_file_contents(filepath, hash_algorithm='sha256'):
  3. """
  4. Hashes the contents of a file using the specified algorithm.
  5. Args:
  6. filepath (str): The path to the file.
  7. hash_algorithm (str): The hashing algorithm to use (e.g., 'md5', 'sha1', 'sha256', 'sha512'). Defaults to 'sha256'.
  8. Returns:
  9. str: The hexadecimal representation of the file's hash, or None if the file does not exist or an error occurs.
  10. """
  11. try:
  12. # Open the file in binary read mode
  13. with open(filepath, 'rb') as f:
  14. # Create a hash object based on the specified algorithm
  15. hasher = hashlib.new(hash_algorithm)
  16. # Read the file in chunks to handle large files efficiently
  17. while True:
  18. chunk = f.read(4096) # Read 4KB chunks
  19. if not chunk:
  20. break
  21. hasher.update(chunk)
  22. # Return the hexadecimal representation of the hash
  23. return hasher.hexdigest()
  24. except FileNotFoundError:
  25. print(f"Error: File not found at {filepath}")
  26. return None
  27. except Exception as e:
  28. print(f"An error occurred: {e}")
  29. return None
  30. if __name__ == '__main__':
  31. # Example usage:
  32. file_path = 'test_file.txt' # Replace with your file path
  33. # Create a dummy file for testing
  34. with open(file_path, 'w') as f:
  35. f.write("This is a test file.\n")
  36. f.write("It contains some text.\n")
  37. # Calculate the SHA256 hash of the file
  38. sha256_hash = hash_file_contents(file_path, 'sha256')
  39. if sha256_hash:
  40. print(f"SHA256 Hash: {sha256_hash}")
  41. # Calculate the MD5 hash of the file
  42. md5_hash = hash_file_contents(file_path, 'md5')
  43. if md5_hash:
  44. print(f"MD5 Hash: {md5_hash}")

Add your comment