Hal*_*ard 13 python macos file-io python-3.x
我正在尝试编写一个打印文件校验和的小脚本(使用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())
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误消息:
Traceback (most recent call last):
File "checksum.py", line 8, in <module>
contents = f.read()
OSError: [Errno 22] Invalid argument
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?我在macOS High Sierra上使用python 3
Sha*_*ger 10
目前已经 几个 问题上的Python从文件句柄读取超过2-4 GB一次历史(最最近版本)(问题的一个不固定的版本也出现在32位Python的建立,在那里他们只是缺乏用于分配缓冲区的虚拟地址空间;不是I/O相关的,而是最常见的啜饮大文件).可用于散列的解决方法是以固定大小的块更新散列(无论如何,这是一个好主意,因为计算RAM大于文件大小是个坏主意).最直接的方法是将代码更改为:
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
Run Code Online (Sandbox Code Playgroud)
如果您感觉很花哨,可以使用两个arg iter和一些functools魔法"简化"循环,用以下内容替换整个while循环:
for block in iter(functools.partial(f.read, 64 * (1 << 20)), b''):
hasher.update(block)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7836 次 |
| 最近记录: |