gpt4 book ai didi

python - 我应该使用python文件的 `readinto`方法吗?

转载 作者:太空狗 更新时间:2023-10-30 00:10:09 28 4
gpt4 key购买 nike

我最近遇到了file对象的readinto方法(在Python 2.7中),它类似于C中的fread。它在某些情况下似乎很方便和强大。我计划使用它将多个文件读取到一个预分配的 numpy 数组中不复制数据

例如

a = np.empty(N)
b = memoryview(a)
fp1.readinto(b[0:100])
fp2.readinto(b[100:200])

fp1.readinto(b[0:100])
fp1.seek(400, 1)
fp1.readinto(b[100:200])

在遇到 readinto 之前,我已经使用 Cythonfread 来完成此操作。所以我很高兴知道一个纯 python 解决方案。

但是它的文档字符串说,

file.readinto?
Type: method_descriptor
String form: <method 'readinto' of 'file' objects>
Namespace: Python builtin
Docstring: readinto() -> Undocumented. Don't use this; it may go away.

不使用这个?发生了什么事?

所以我很困惑,我应该使用 readinto 吗?它可能会导致任何不必要的问题?

对于上面的代码,是否有任何替代实现,既没有readinto,又避免数据复制? (为了避免复制意味着 np.concatenatenp.stack 不是一个好的选择。)

欢迎任何建议!谢谢。

--------更新--------

看来我可以在标准库中使用io.FileIO 而不是内置函数open。它看起来不错,所以我将其发布为答案。

仍然欢迎任何评论或其他解决方案!

--------更新--------

如果你遇到同样的问题,你可能想看看下面的评论
Andrea Corbellini 和 Padraic Cunningham。

最佳答案

如果您不确定,您可以使用 python 标准库中的 io.FileIO 而不是内置函数 openfile使用 file.readinto

这是文档字符串:

#io.FileIO.readinto?
Type: method_descriptor
String form: <method 'readinto' of '_io.FileIO' objects>
Docstring: readinto() -> Same as RawIOBase.readinto().

可以找到io.RawIOBase.readinto的文档here .

class io.RawIOBase

...

readinto(b)

Read up to len(b) bytes into bytearray b and return the number of bytes read. If the object is in non-blocking mode and no bytes are available, None is returned.

它在 Python 2 和 3 中都可用。

关于python - 我应该使用python文件的 `readinto`方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34768958/

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