Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

CRC32 on files

0 views
Skip to first unread message

Adonis Vargas

unread,
Jan 4, 2002, 2:03:18 AM1/4/02
to
how do i run a CRC32 checksum on a file with python? or do i have the
concept all wrong.
pardon my ignorance, first time i even touch upon this subject.

thanks in advance.

Adonis


Alex Martelli

unread,
Jan 4, 2002, 5:29:48 AM1/4/02
to
"Adonis Vargas" <delt...@telocity.com> wrote in message
news:3c355398$1...@nopics.sjc...

> how do i run a CRC32 checksum on a file with python? or do i have the


For example:

def crc32_of_file(filepath):
from zlib import crc32
fileobj = open(filepath,'rb')
current = 0
while 1:
buffer = fileobj.read(8192)
if not buffer: break
current = crc32(buffer, current)
fileobj.close()
return current

or, if you know the file ain't TOO huge, and are willing to trust
"automatic closure" of the opened file (explicit close is better...):

import zlib
thevalueyouwant = zlib.crc32(open(filepath,'rb').read())


Alex

Nikolai Kirsebom

unread,
Jan 4, 2002, 9:24:43 AM1/4/02
to
Script I'm using to generate CRC on set of files:

#
# Generate CRC32 on file
#

import zlib
import array
import sys
import os

if __name__ == '__main__':
if len(sys.argv) < 2:
print "Usage: python GenCrc.py filename filename ..."
for fn in sys.argv[1:]:
fileSize = os.stat(fn)[6]
f = open(fn, "rb")
v = array.array('B')
try:
v.fromfile(f, fileSize)
i = zlib.crc32(v.tostring())
print "Crc32 of %s is :%d:" % (fn, i)
except:
print "Not able to read / generate CRC for file :%s:" %
(fn)


Nikolai

Pete Shinners

unread,
Jan 4, 2002, 11:52:28 AM1/4/02
to
Adonis Vargas wrote:


hmm, you can use the SHA module to get a "SHA" checksum for a file. it
is a bit more intensive but also probably more 'unique' then crc.

import sha
def get_sha_checksum(filename):
filedata = open(filename).read()
return sha.new(filedata).hexdigest()

this will return a 40byte string of hex data. it also appears you can
get a straight up CRC32 checksum as well...

import binascii
def get_crc_checksum(filename):
filedata = open(filename).read()
return binascii.crc32(filedata)


that should do you pretty good. goodluck

Laurent Szyster

unread,
Jan 4, 2002, 2:11:09 PM1/4/02
to
Alex Martelli wrote:
>
> or, if you know the file ain't TOO huge, and are willing to trust
> "automatic closure" of the opened file (explicit close is better...):

why?


Laurent

0 new messages