[英]memory efficient way to write an uncompressed file from a gzip file
使用Python 3.5
我正在解壓縮gzip文件,正在寫入另一個文件。 研究完內存不足問題后,我在文檔中找到了gzip模塊的示例:
import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
這確實可以壓縮,我想解壓縮,所以我認為我可以反轉模式,
with open(unzipped_file, 'wb') as f_out, gzip.open(zipped_file, 'rb') as f_in:
shutil.copyfileobj(f_in, f_out)
我的問題是,為什么我遇到以下問題:
with gzip.open(zipped_file, 'rb') as zin, open(unzipped_file, 'wb') as wout:
wout.write(zin.read())
要么我躺在了最后一根稻草上,要么我天真地相信文件將像生成器一樣工作並以流方式進行解壓縮過程,而占用的內存很少。 這兩種方法應該等效嗎?
這是shutil.copyfileObj
方法。
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)
它讀取文件的長度為16 * 1024。 而且,當您嘗試撤消該過程時,您並沒有考慮文件的大小,因為文件的大小將被讀取到內存中並使您陷入內存問題。
而不是飢餓的記憶(天真)
import gzip
with gzip.open(zipped_file, 'rb') as zin, open(unzipped_file, 'wb') as wout:
wout.write(zin.read())
根據先前的答案,我對此進行了測試:
import gzip
block_size = 64*1024
with gzip.open(zipped_file, 'rb') as zin, open(unzipped_file, 'wb') as wout:
while True:
uncompressed_block = zin.read(block_size)
if not uncompressed_block:
break
wout.write(uncompressed_block)
已在4.8G文件上驗證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.