Does hashlib support a file mode?

Peter Otten __peter__ at web.de
Wed Jul 6 12:26:09 EDT 2011


Phlip wrote:

> Tx, all!. But...
> 
>> For example I use this function to copy a stream and return a SHA512 and
>> the output streams size:
>>
>> def write(self, in_handle, out_handle):
>> m = hashlib.sha512()
>> data = in_handle.read(4096)
>> while True:
>> if not data:
>> break
>> m.update(data)
>> out_handle.write(data)
>> data = in_handle.read(4096)
>> out_handle.flush()
>> return (m.hexdigest(), in_handle.tell())
> 
> The operation was a success but the patient died.
> 
> My version of that did not return the same hex digest as the md5sum
> version:
> 
> 
> def file_to_hash(path, m = hashlib.md5()):
> 
>     with open(path, 'r') as f:
> 
>         s = f.read(8192)
> 
>         while s:
>             m.update(s)
>             s = f.read(8192)
> 
>     return m.hexdigest()
> 
> You'll notice it has the same control flow as yours.
> 
> That number must eventually match an iPad's internal MD5 opinion of
> that file, after it copies up, so I naturally cannot continue working
> this problem until we see which of the two numbers the iPad likes!

- Open the file in binary mode.
- Do the usual dance for default arguments:
    def file_to_hash(path, m=None):
        if m is None:
            m = hashlib.md5()





More information about the Python-list mailing list