Using Python to generate the file md5 checksum function,
Preface
In linux, there is a command called md5sum, which can generate the md5 value of the file. Generally, the result is recorded in a file for verification. For example, it will be used as follows:
[crazyant@localhost PythonMd5]$ more sample_file www.crazyant.netwww.51projob.com[crazyant@localhost PythonMd5]$ md5sum sample_file > sample_file.md5file[crazyant@localhost PythonMd5]$ more sample_file.md5file 311d384505e3622ccf85d88930e2b0a0 sample_file[crazyant@localhost PythonMd5]$ md5sum -c sample_file.md5file sample_file: OK
Wheremd5sum -c
Used to check whether the generated md5 value is correct.
Use python to generate the file's md5 value and generate the same result file as the md5sum result.
Python can use the md5 module of hashlib to generate an md5 verification code for the file content. To generate a result file that is the same as md5sum, you only need to output a line of MD5 result value and file name, there are two spaces in the middle of the output.
Test code:
#-*-Encoding: UTF-8-*-from hashlib import md5import OS def generate_file_md5value (fpath): ''' takes the file path as the parameter, return the md5 value of the file ''m = md5 () # You need to use the binary format to read the file content a_file = open (fpath, 'rb') m. update (a_file.read () a_file.close () return m. hexdigest () def generate_file_md5sumFile (fpath): fname = OS. path. basename (fpath) fpath_md5 = "% s. md5 "% fpath fout = open (fpath_md5," w ") fout. write ("% s \ n" % (generate_file_md5value (fpath), fname. strip () print "generate success, fpath: % s" % fpath_md5 fout. flush () fout. close () if _ name _ = "_ main _": fpath = "/home/users/workbench/PythonMd5/sample_file" # Test 1: obtain the md5 string print generate_file_md5value (fpath) using the file path as the parameter # Test 2: generate the same result as the linux Command md5sum. md5 file generate_file_md5sumFile (fpath)
Running result:
[crazyant@localhost PythonMd5]$ python generateMd5file.py311d384505e3622ccf85d88930e2b0a0generate success, fpath:/home/crazyant/workbench/PythonMd5/sample_file.md5[crazyant@localhost PythonMd5]$ md5sum -c sample_file.md5sample_file: OK
Notes
If the code developed in windows is directly submitted to linux for running, it is often because the line break in windows is \ r \ n and linux is \ n, which leads to code execution failure, generally, you need to perform a conversion.
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message. Thank you for your support.