Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python &引用;OSError:[Errno 22]无效参数“;当读取()并读取一个大文件时_Python_Python 3.x_Macos_File Io - Fatal编程技术网

Python &引用;OSError:[Errno 22]无效参数“;当读取()并读取一个大文件时

Python &引用;OSError:[Errno 22]无效参数“;当读取()并读取一个大文件时,python,python-3.x,macos,file-io,Python,Python 3.x,Macos,File Io,我正在尝试编写一个小脚本,用于打印文件的校验和(使用以下代码): 但我收到以下错误消息: Traceback (most recent call last): File "checksum.py", line 8, in <module> contents = f.read() OSError: [Errno 22] Invalid argument 回溯(最近一次呼叫最后一次): 文件“checksum.py”,第8行,在 contents=f.read() OSEr

我正在尝试编写一个小脚本,用于打印文件的校验和(使用以下代码):

但我收到以下错误消息:

Traceback (most recent call last):
  File "checksum.py", line 8, in <module>
    contents = f.read()
OSError: [Errno 22] Invalid argument
回溯(最近一次呼叫最后一次):
文件“checksum.py”,第8行,在
contents=f.read()
OSError:[Errno 22]参数无效
我做错了什么?我在macOS High Sierra上使用Python3

在python(最新版本中已修复)的历史上,一次从文件句柄读取超过2-4 GB的数据(这个问题的一个不可压缩版本也发生在32位的Python构建上,它们只是缺少分配缓冲区的虚拟地址空间;与I/O无关,但最常见的情况是对大文件进行slurp处理)。散列的一个解决方法是在固定大小的块中更新散列(无论如何,这是个好主意,因为指望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
或者在Python 3.8+上,它更简单,不需要导入或不可读的代码:

while block := f.read(64 * (1 << 20)):  # Assigns and tests result in conditional!
    hasher.update(block)

while block:=f.read(64*(1Wow)这可能更简单。只需逐行读取文件:

with open('big-file.txt') as f:
  for i in f:
    print(i)

无法复制。在尝试获取任何文件或仅获取特定文件的校验和时会发生这种情况吗?您使用的是Python 2还是Python 3?为什么错误消息会显示
contents=f.read()
第8行是这里给出的代码的第6行吗?您尝试过其他文件吗?Python只翻译它从操作系统(
EINVAL
)获得的错误代码,错误代码很可能来自文件系统驱动程序本身(所以它可能是其中的错误)。通常,
EINVAL
响应读取意味着fd号是错误的,但这是不常见的情况,因为Python自己控制fd号的正确性。@roganjosh:这里给出的答案只适用于Windows系统。这个问题似乎与macOS上的问题有关。我现在尝试了其他文件,它们工作正常。原始的.img不过,文件仍然给出了相同的错误消息。可能是因为它的大小为4,92 GB吗?@Hallvard:您使用的是什么版本的Python?您使用的是32位系统吗?根据这两个问题的答案,可能会出现一些问题。哇,太完美了。谢谢!
while block := f.read(64 * (1 << 20)):  # Assigns and tests result in conditional!
    hasher.update(block)
with open('big-file.txt') as f:
  for i in f:
    print(i)