Python计算大文件crc32值

直接看代码吧☺

#!usr/bin/env python  
#-*- coding:utf-8 -*-  
""" 
@author: guoqianqian 
@file: mycrc32.py 
@time: 2017/07/06 
@desc: 
"""

import zlib
import os
import sys

def crc32(filepath):
    block_size = 1024 * 1024
    crc = 0

    try:
        fd = open(filepath, 'rb')
        while True:
            buffer = fd.read(block_size)
            if len(buffer) == 0: # EOF or file empty. return hashes
                fd.close()
                if sys.version_info[0] < 3 and crc < 0:
                    crc += 2 ** 32
                return crc#返回的是十进制的值
            crc = zlib.crc32(buffer, crc)
    except Exception as e:
        if sys.version_info[0] < 3:
            error = unicode(e)
        else:
            error = str(e)
        return 0, error

if __name__ == "__main__":
    crc = crc32("./test")
    print hex(crc)

你可能感兴趣的:(Python)