相关疑难解决方法(0)

readinto() 替换?

在 Python 中使用直接方法复制文件通常是这样的:

def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)
Run Code Online (Sandbox Code Playgroud)

(顺便说一下,这段代码来自shutil.py)。

不幸的是,这在我的特殊用例中存在缺陷(涉及线程和非常大的缓冲区)[斜体部分稍后添加]。首先,这意味着每次调用 read() 都会分配一个新的内存块,当 buf 在下一次迭代中被覆盖时,该内存将被释放,只是为了相同的目的再次分配新内存。这会减慢整个过程并给主机带来不必要的负载。

为了避免这种情况,我使用了 file.readinto() 方法,不幸的是,该方法已被记录为已弃用且“请勿使用”:

def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    buffer = array.array('c')
    buffer.fromstring('-' * length)
    while True:
        count = fsrc.readinto(buffer)
        if count == 0:
            break
        if count != len(buffer):
            fdst.write(buffer.toString()[:count])
        else:
            buf.tofile(fdst)
Run Code Online (Sandbox Code Playgroud)

我的解决方案有效,但也有两个缺点:首先,不使用 readinto()。它可能会消失(文档说)。其次,使用 readinto() …

python arrays fromfile

4
推荐指数
1
解决办法
3876
查看次数

标签 统计

arrays ×1

fromfile ×1

python ×1