Python writes the MD5 value of a file for automation

Source: Internet
Author: User

Using Python to get the MD5 value of a file is a simple thing, Python provides the MD5 and hashlib two modules, you can get the MD5 value of the file.

The code is as follows:

#获取文件的MD5值, for small file    def getFileMD5 (self,filepath):        if Self.isfile (filepath):            f = open (filepath, ' RB ')            md5obj = hashlib.md5 ()            md5obj.update (F.read ())            hash = md5obj.hexdigest ()            f.close ()            return STR (hash). Upper ()        return None

The above code has been applied with the MD5 value of getting most files.


However, looking at the code, you will find that there is actually a process of reading the file when getting the MD5 value. This will have a problem, if the file is very large, larger than the memory of the machine, the above code will have a problem, the solution is to be read several times, the code is as follows:

#获取文件的MD5值, for larger files    def getBigFileMD5 (self,filepath):        if Self.isfile (filepath):            md5obj = HASHLIB.MD5 ()            maxbuf = 8192            f = open (filepath, ' RB ') while            True:                buf = F.read (maxbuf)                if not buf:                    break< C13/>md5obj.update (BUF)            f.close ()            hash = md5obj.hexdigest ()            return str (hash). Upper ()        return None

In addition, it is important to note that:The MD5 module has been canceled in Python version 3.2, so it is recommended to use the Hashlib module when getting MD5.

Python writes the MD5 value of a file for automation

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.