zoukankan      html  css  js  c++  java
  • python 通过文件路径获取文件hash值

     1 import hashlib
     2 import os,sys
     3 
     4 def CalcSha1(filepath):
     5     with open(filepath,'rb') as f:
     6         sha1obj = hashlib.sha1()
     7         sha1obj.update(f.read())
     8         hash = sha1obj.hexdigest()
     9         print(hash)
    10         return hash
    11 
    12 def CalcMD5(filepath):
    13     with open(filepath,'rb') as f:
    14         md5obj = hashlib.md5()
    15         md5obj.update(f.read())
    16         hash = md5obj.hexdigest()
    17         print(hash)
    18         return hash
    19 
    20 if __name__ == "__main__":
    21     if len(sys.argv)==2 :
    22         hashfile = sys.argv[1]
    23         if not os.path.exists(hashfile):
    24             hashfile = os.path.join(os.path.dirname(__file__),hashfile)
    25             if not os.path.exists(hashfile):
    26                 print("cannot found file")
    27             else
    28             CalcMD5(hashfile)
    29     else:
    30         CalcMD5(hashfile)
    31         #raw_input("pause")
    32 else:
    33     print("no filename")
     

    使用Python进行文件Hash计算有两点必须要注意:

    1、文件打开方式一定要是二进制方式,既打开文件时使用b模式,否则Hash计算是基于文本的那将得到错误的文件Hash(网上看到有人说遇到Python的Hash计算错误在大多是由于这个原因造成的)。

    2、对于MD5如果需要16位(bytes)的值那么调用对象的digest()而hexdigest()默认是32位(bytes),同理Sha1的digest()和hexdigest()分别产生20位(bytes)和40位(bytes)的hash值

  • 相关阅读:
    log4j.properties 配置示例
    spark去重计数操作(代码示例)
    mysql数据库
    Mysql之sql语句操作
    mysql修改root密码的多种方法
    mysql的主从复制过程
    mysql命令用法复习笔记
    Linux下如何查看系统启动时间和运行时间安装时间
    一键系统优化15项脚本
    MongoDB
  • 原文地址:https://www.cnblogs.com/SunboyL/p/Python_Hash.html
Copyright © 2011-2022 走看看