2011-03-10 42 views
6

我正在一個內存受限的環境中工作,我需要製作SQL轉儲文件。如果我使用內置的tarfile module內置的python文件,它是在內存中保存或在創建時寫入磁盤的'.tar'文件?Python的`tarfile`模塊是否存儲它在內存中構建的檔案?

例如,在下面的代碼中,如果huge_file.sql是2GB,則tar變量在內存中佔用2GB?

import tarfile 

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

回答

5

不,它不會將它加載到內存中。鏈接到源

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 
+0

+1:可以讀取source for tarfile地看到,它的使用copyfileobj,這是使用固定大小的緩衝區拷貝從文件到壓縮包。開發文檔現在也有鏈接http://docs.python.org/dev/library/tarfile – jfs 2011-03-10 22:35:38

相關問題