Python的`tarfile`模块会将构建的归档存储在内存中吗?

6 投票
1 回答
1027 浏览
提问于 2025-04-16 13:27

我正在一个内存有限的环境中工作,需要制作SQL转储的归档文件。如果我使用Python内置的tarfile模块,那么在创建'.tar'文件时,它是保存在内存中,还是直接写入磁盘呢?

举个例子,在下面的代码中,如果huge_file.sql是2GB,那么tar这个变量会在内存中占用2GB吗?

import tarfile

tar = tarfile.open("my_archive.tar.gz")), "w|gz")
tar.add('huge_file.sql')
tar.close()

1 个回答

5

不是的,它并不是把所有内容都加载到内存中。你可以查看tarfile的源代码,你会发现它使用了copyfileobj这个方法,这个方法是用一个固定大小的缓冲区来从文件复制内容到压缩包里的。

def copyfileobj(src, dst, length=None):
    """Copy length bytes from fileobj src to fileobj dst.
       If length is None, copy the entire content.
    """
    if length == 0:
        return
    if length is None:
        shutil.copyfileobj(src, dst)
        return

    BUFSIZE = 16 * 1024
    blocks, remainder = divmod(length, BUFSIZE)
    for b in xrange(blocks):
        buf = src.read(BUFSIZE)
        if len(buf) < BUFSIZE:
            raise IOError("end of file reached")
        dst.write(buf)

    if remainder != 0:
        buf = src.read(remainder)
        if len(buf) < remainder:
            raise IOError("end of file reached")
        dst.write(buf)
    return

撰写回答