Python Program to find Hash of File

By | October 3, 2021
Python Program to find Hash of File

In this article, we have provided a python source code that can find the hash of a file and display it

Prerequisite topics to create this program.

  • Python Functions
  • Python user-defined functions
  • Python Modules
  • Python hashlib library
  • Python File I/O

A hash function accepts the data and returns a fixed-length bit string. Hash functions mostly used in cryptography and authentications. There are various hashing functions such as MD5, SHA-1, etc. In python, we have an inbuilt library known as hashlib which use the SHA-1 hashing algorithms and provide a 160 bits long digest message, a digest message is the string output of the hash function.

We can pass any type of data to the hash function.

Python Program to find Hash of File:


import hashlib

def find_hash(filename):
    # Create a hash Object

   h_o = hashlib.sha1()

   # open the data in binary mode
   with open(filename,'rb') as file:

       # loop till the end of the file
       chunk = 0
       while chunk != b'':
           # read only 1024 bytes at a time
           chunk =

   # return the hex representation of digest
   return h_o.hexdigest()

message = find_hash("image.jpg")



Behind the Code:

Here we have created a hash function by name find_hash() which accept the file as an argument. Inside the function using the with open(filename,'rb') as file statement we open the file in binary mode and using the while chunk != b'':  statement looped through its binary data and with each iteration of the while loop the hash object h_o read the 1024 bytes of data and update the hash function. Once the while loop ends we return the hash message in hexadecimal representation.


People are also reading:

Author: Vinay Singh

I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Leave a Reply

Your email address will not be published.