zoukankan      html  css  js  c++  java
  • 使用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))

    运行截图:

  • 相关阅读:
    飞机大战4-我的子弹
    飞机大战3-我的飞机
    飞机大战1-分析设计
    继承
    常见题
    42个例子算法
    心跳
    tomcat
    service
    URI URL
  • 原文地址:https://www.cnblogs.com/zhangwei22/p/14155021.html
Copyright © 2011-2022 走看看