Table of Content
Sure, Here’s a Python program to find the hash of a file using the hashlib library:
import hashlib # Open file for reading in binary mode ('rb') with open('file.txt', 'rb') as f: # Instantiate a new SHA-256 hash object sha256_hash = hashlib.sha256() # Read the file in chunks and update the hash object for chunk in iter(lambda: f.read(4096), b''): sha256_hash.update(chunk) # Get the hexadecimal representation of the hash digest hash_hex = sha256_hash.hexdigest() # Print the hash print('The SHA-256 hash of file.txt is:', hash_hex)
Make sure to replace ‘file.txt’ with the name of your file. This program reads the file in chunks to avoid trying to load the entire file into memory at once, which can cause performance problems for large files.
This program uses the SHA-256 hash algorithm to calculate the hash digest of the file. You can use other hash algorithms such as SHA-1 or MD5 by instantiating a different hash object (e.g.
I hope this helps you find the hash of a file using Python!