使用Python腳本計算文件MD5值


為了方便在Windows環境計算文件MD5值。

使用Python完成一個腳本,實現md5sum功能。

代碼:

import os
import sys
import hashlib


def md5sum(file):
    if not os.path.exists(file):
        return "md5sum: {}: No such file or directory".format(file)
    elif os.path.isdir(file):
        return "md5sum: {}: Is a directory".format(file)
    elif os.path.isfile(file):
        with open(file, 'rb') as fd:
            data = fd.read()
        return "{}  {}".format(hashlib.md5(data).hexdigest(), file)
    else:
        return "md5sum: {}: Unexpected error".format(file)


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: md5sum.py filename")
        sys.exit()

    file_name = sys.argv[1]

    if file_name.endswith("*"):
        if file_name == "*":
            file_path = os.path.dirname(os.path.realpath(__file__))
        else:
            file_path = file_name[:-1]

        if os.path.exists(file_path):
            files = os.listdir(file_path)
            for f in files:
                print(md5sum(os.path.join(file_path, f)))
        else:
            print("md5sum: {}: No such file or directory".format(file_path))

    else:
        print(md5sum(file_name))

運行截圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM