简体   繁体   English

用python修改gzip压缩文件

[英]modify gzipped file with python

I am trying to modify the gzipped file. 我正在尝试修改压缩文件。 Here is my code: 这是我的代码:

with tempfile.TemporaryFile() as tmp:
    with gzip.open(fname, 'rb') as f:
        shutil.copyfileobj(f, tmp)
    # do smth here later
    with gzip.open(fname, 'wb') as f:
        shutil.copyfileobj(tmp, f)

I removed all modifications, only left the read and write. 我删除了所有修改,只保留了读写功能。 On output I get the empty gzipped file. 在输出时,我得到了空的gzip压缩文件。 What's wrong with this? 这怎么了 (Python 2.7.6, Linux) (Python 2.7.6,Linux)

You need to point to the beginning of the temporary file after copy: 复制后,您需要指向临时文件的开头:

with tempfile.TemporaryFile() as tmp:
    with gzip.open(fname, 'rb') as f:
        shutil.copyfileobj(f, tmp)
        tmp.seek(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM