python-oxlib/oxlib/file.py

57 lines
1.5 KiB
Python
Raw Normal View History

2008-04-27 16:54:37 +00:00
# -*- coding: utf-8 -*-
2008-06-19 09:21:21 +00:00
# vi:si:et:sw=4:sts=4:ts=4
2008-07-06 13:00:06 +00:00
# GPL 2008
2009-05-28 17:00:30 +00:00
from __future__ import division
2008-04-27 16:54:37 +00:00
import os
2009-03-16 17:15:14 +00:00
import hashlib
2009-05-28 17:00:30 +00:00
import sys
import struct
2008-04-27 16:54:37 +00:00
def sha1sum(filename):
2009-03-16 17:15:14 +00:00
sha1 = hashlib.sha1()
2008-06-19 09:21:21 +00:00
file=open(filename)
2008-04-27 16:54:37 +00:00
buffer=file.read(4096)
2008-06-19 09:21:21 +00:00
while buffer:
sha1.update(buffer)
buffer=file.read(4096)
file.close()
return sha1.hexdigest()
2008-04-27 16:54:37 +00:00
2009-05-28 17:00:30 +00:00
'''
os hash - http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes
'''
def oshash(filename):
try:
longlongformat = 'q' # long long
bytesize = struct.calcsize(longlongformat)
f = open(filename, "rb")
filesize = os.path.getsize(filename)
hash = filesize
if filesize < 65536:
return "SizeError"
for x in range(int(65536/bytesize)):
buffer = f.read(bytesize)
(l_value,)= struct.unpack(longlongformat, buffer)
hash += l_value
hash = hash & 0xFFFFFFFFFFFFFFFF #to remain as 64bit number
f.seek(max(0,filesize-65536),0)
for x in range(int(65536/bytesize)):
buffer = f.read(bytesize)
(l_value,)= struct.unpack(longlongformat, buffer)
hash += l_value
hash = hash & 0xFFFFFFFFFFFFFFFF
f.close()
returnedhash = "%016x" % hash
return returnedhash
except(IOError):
return "IOError"
2008-04-27 16:54:37 +00:00