Calculate the MD5 value of a file in Python

Source: Internet
Author: User
Tags md5 in python

The MD5 implementation is built into Python, which is the MD5 module, so it's easy to deal with the problem of comparing two files consistently. such as the following code fragment:

Import Os,sys,md5

F1 = open (' F:/1.txt ', ' R ')

F2 = open (' F:/1.txt ', ' R ')

Print md5.new (F1.read ()). Digest () = = Md5.new (F2.read ()). Digest ()

The above processing will have memory problems when dealing with larger files (such as hundreds of M files).


----------------------------------------------another way to implementCode:Import MD5
Import Sys

def sumfile (fobj):
m = Md5.new ()
While True:
D = Fobj.read (8096)
If not D:
Break
M.update (d)
Return M.hexdigest ()


def md5sum (fname):
If fname = = '-':
ret = Sumfile (Sys.stdin)
Else
Try
f = File (fname, ' RB ')
Except
Return ' Failed to open file '
ret = Sumfile (f)
F.close ()
return ret


if __name__ = = ' __main__ ':
For fname in sys.argv[1:]:
print '%32s%s '% (md5sum (fname), fname)

Related Article

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.