python · March 25, 2023 0

How to Find Hash of File using Python

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:, b''):

# 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. hashlib.sha1() or hashlib.md5()).

I hope this helps you find the hash of a file using Python!

%d bloggers like this: