【问题标题】:modify gzipped file with python用python修改gzip文件
【发布时间】:2015-10-30 16:57:36
【问题描述】:

我正在尝试修改 gzip 压缩文件。 这是我的代码:

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)

我删除了所有修改,只留下了读写。在输出时,我得到空的 gzip 文件。这有什么问题? (Python 2.7.6,Linux)

【问题讨论】:

    标签: python io gzip


    【解决方案1】:

    复制后需要指向临时文件的开头:

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

    【讨论】:

    • 正确。愚蠢的我。稍后会接受它,现在必须运行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多