gpt4 book ai didi

python - 查看 Python 3 中读取了多少 `file.read`

转载 作者:行者123 更新时间:2023-12-01 09:04:25 25 4
gpt4 key购买 nike

Read and return up to size bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. An empty bytes object is returned if the stream is already at EOF.

If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent.

A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.

io.BufferedIOBase.read

如果读取操作返回的结果的长度可能小于给定或预期的长度;并且仍然没有表明已达到 EOF,哪种可靠的分块方式最可靠?

import os
import io

def reliable_read(file_obj, amount=None, chk_size=2):
file_size = os.fstat(file_obj.file_no()).st_size
data = b"" if isinstance(file_obj, io.BufferedReader) else ""
amount_read = 0

if amount is None:
amount = file_size
while amount_read < amount:
data += file_obj.read(chk_size)
return data

最初我认为出于某种原因, block 大小越小,读取完全执行的概率就越高;但是我并不完全知道这是否属实 - 因此它测试了上述函数的可靠性。它的效率也相当低,因为 chk_size 接近 1,函数调用量接近 file_size,这对于真正的大文件来说并不是最佳选择。

本质上,在不使用 CFFI 导入 fopenfreadfclose 的情况下 - 存在哪些内置函数或库可以实现可靠的读取,也在我的标题的本质之内;返回准确读取量的函数,通过引用将读取缓冲区放入列表中,或者作为 (data, n_read) 的元组。

最佳答案

在您引用的文档中注意:

multiple raw reads may be issued to satisfy the byte count

这意味着这个循环没有用。原始读取是操作系统使用 read() 执行的读取,它返回的数据可能少于某些输入流上请求的数据。

while amount_read < amount:
data += file_obj.read(chk_size)

(加上循环没有更新amount_read,所以我怀疑它有一个错误)

由于您使用的是 python 文件接口(interface)(而不是 os.read),python 将在内部执行此操作,如果需要一个或多个内部原始读取,则过程中可能会出现错误完成操作失败。

你无法控制内部读取,所以你只需要做:

data = file_obj.read(amount)

如果您不想使用pyhton接口(interface),那么请使用os.read,它具有您必须管理的完全控制和原始错误检查功能。

关于python - 查看 Python 3 中读取了多少 `file.read`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52187121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com