- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Find Hash of File using Python?
You can find the hash of a file using the hashlib library. Note that file sizes can be pretty big. Its best to use a buffer to load chunks and process them to calculate the hash of the file. You can take a buffer of any size.
Example
import sys import hashlib BUF_SIZE = 32768 # Read file in 32kb chunks md5 = hashlib.md5() sha1 = hashlib.sha1() with open('program.cpp', 'rb') as f: while True: data = f.read(BUF_SIZE) if not data: break md5.update(data) sha1.update(data) print("MD5: {0}".format(md5.hexdigest())) print("SHA1: {0}".format(sha1.hexdigest()))
Output
This will give the output
MD5: 7481a578b20afc6979148a6a5f5b408d SHA1: f7187ed8b258baffcbff2907dbe284f8f3f8d8c6
Advertisements