"OSError: [Errno 22] Invalid argument" when reading () with a huge file

I am trying to write a small script that prints a checksum of a file (using some code from https://gist.github.com/Zireael-N/ed36997fd1a967d78cb2 )

import sys
import os
import hashlib

file = '/Users/Me/Downloads/2017-11-29-raspbian-stretch.img'

with open(file, 'rb') as f:
    contents = f.read()
    print('SHA256 of file is %s' % hashlib.sha256(contents).hexdigest())

But I get the following error message:

Traceback (most recent call last):
  File "checksum.py", line 8, in <module>
    contents = f.read()
OSError: [Errno 22] Invalid argument

What am I doing wrong? I am using python 3 on macOS High Sierra

+4
source share
1 answer

Python ( ), 2-4 ( 32- Python, , I/O, ). , , ( , , , ). - :

with open(file, 'rb') as f:
    hasher = hashlib.sha256()  # Make empty hasher to update piecemeal
    while True:
        block = f.read(64 * (1 << 20)) # Read 64 MB at a time; big, but not memory busting
        if not block:  # Reached EOF
            break
        hasher.update(block)  # Update with new block
print('SHA256 of file is %s' % hasher.hexdigest())  # Finalize to compute digest

, "" -arg iter functools, while :

for block in iter(functools.partial(f.read, 64 * (1 << 20)), b''):
    hasher.update(block)
+4

Source: https://habr.com/ru/post/1691810/


All Articles