Python calculates the md5 value of a file instance

Reprinted from http://www.jb51.net/article/102919.htm


Small file handling method

  1. import hashlib
  2. import them
  3. def get_md5_01(file_path):
  4. md5 = None
  5. if os.path.isfile(file_path):
  6. f = open(file_path,'rb')
  7. md5_obj = hashlib.md5()
  8. md5_obj.update(f.read())
  9. hash_code = md5_obj.hexdigest()
  10. f.close()
  11. md5 = str(hash_code).lower()
  12. return md5
  13. if __name__ == "__main__":
  14. file_path = r'D:\test\test.jar'
  15. md5_01 = get_md5_01(file_path)
  16. print(md5_01)


Larger file handling methods

  1. import hashlib
  2. import them
  3. def get_md5_02(file_path):
  4. f = open(file_path,'rb')
  5. md5_obj = hashlib.md5()
  6. while True:
  7. d = f.read(8096)
  8. if not d:
  9. break
  10. md5_obj.update(d)
  11. hash_code = md5_obj.hexdigest()
  12. f.close()
  13. md5 = str(hash_code).lower()
  14. return md5
  15. if __name__ == "__main__":
  16. file_path = r'D:\test\test.jar'
  17. md5_02 = get_md5_02(file_path)
  18. print(md5_02)



Related: Python calculates the md5 value of a file instance