Python calculates the md5 value of a file,

Source: Internet
Author: User

Python calculates the md5 value of a file,

Small file processing method:

import hashlibimport osdef get_md5_01(file_path):  md5 = None  if os.path.isfile(file_path):    f = open(file_path,'rb')    md5_obj = hashlib.md5()    md5_obj.update(f.read())    hash_code = md5_obj.hexdigest()    f.close()    md5 = str(hash_code).lower()  return md5if __name__ == "__main__":  file_path = r'D:\test\test.jar'  md5_01 = get_md5_01(file_path)  print(md5_01)

Processing of large files:

import hashlibimport osdef get_md5_02(file_path):  f = open(file_path,'rb')    md5_obj = hashlib.md5()  while True:    d = f.read(8096)    if not d:      break    md5_obj.update(d)  hash_code = md5_obj.hexdigest()  f.close()  md5 = str(hash_code).lower()  return md5if __name__ == "__main__":  file_path = r'D:\test\test.jar'  md5_02 = get_md5_02(file_path)  print(md5_02)

NOTE: For the same file, the md5 calculated by the two methods is the same.

Note: The above code has passed the test in Python 3.x.

The above example of the md5 value of the python computing file is all the content shared by Alibaba Cloud. I hope to give you a reference and support for the help house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.