Skip to content

Instantly share code, notes, and snippets.

@hypebeast
Created December 28, 2011 17:43
Show Gist options
  • Save hypebeast/1528840 to your computer and use it in GitHub Desktop.
Save hypebeast/1528840 to your computer and use it in GitHub Desktop.
Calculate the checksum of a file
#!/usr/bin/env python
'''
Per's SFV is a simple Simple File Verificator that you can use to
verify that a file has not changed.
Copyright (C) 2006 Per Myren <per.myren@gmail.com>
Distributed under the GPL v2
modified by jason moiron to remove wx cruft and to allow file objects
as arguments to CheckSum()
usage:
CheckSum(file_or_filename).getfilecrc()
'''
import zlib, md5, struct, binascii, os
class CRC32:
def __init__(self, s=''):
self.value = zlib.crc32(s)
def update(self, s):
self.value = zlib.crc32(s, self.value)
def digest(self):
return struct.pack('>I',self.value)
class CheckSum:
def __init__(self, filename):
self.filename = filename
def _getCheckSum(self, filename, checksumtype):
try:
if isinstance(filename, file):
f = filename
elif isinstance(filename, str):
f = file(filename, 'rb')
while True:
x = f.read(65536)
if not x:
f.close()
return checksumtype.digest()
checksumtype.update(x)
except (IOError, OSError):
return "No such file"
def getfilemd5(self):
return binascii.hexlify(self._getCheckSum(self.filename, md5.new()))
def getfilecrc(self):
return binascii.hexlify(self._getCheckSum(self.filename, CRC32()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment