我在一个内存受限的环境中工作,我需要对 SQL 转储进行归档。如果我使用内置的 python tarfile
module “.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()
最佳答案
不,它没有将它加载到内存中。您可以阅读 source for tarfile可以看到它正在使用 copyfileobj
,它使用固定大小的缓冲区从文件复制到 tarball:
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
关于python - Python 的 `tarfile` 模块是否将它正在构建的文件存储在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5264755/