ZipFile不会在归档文件中存储任何文本

时间:2014-08-24 00:54:44

标签: python zipfile

以下代码导致zip中的文件为空,而不是其中包含some text

def func(path):
    with tempfile.NamedTemporaryFile() as f:
        f.write('some text')
        with zipfile.ZipFile(path + '.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
            zf.write((f.name), path)

1 个答案:

答案 0 :(得分:1)

flush添加到文件对象:

def func(path):
    with tempfile.NamedTemporaryFile() as f:
        f.write('some text')
        f.flush()  # <-- lifesaver
        with zipfile.ZipFile(path + '.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
            zf.write((f.name), path)

此问题也会影响正常(非临时)文件,因此他们还需要flush处理:

def func(path):
    with open(path, 'w') as f:
        f.write('some text')
        f.flush()  # <-- lifesaver
        with zipfile.ZipFile(path + '.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
            zf.write(path)

或者,减去第二个with块将避免使用flush,因为当该块退出时文件会自动关闭,从而增加了刷新的可能性:

def func(path):
    with open(path, 'w') as f:
        f.write('some text')
    with zipfile.ZipFile(path + '.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
        zf.write(path)

请注意,这仅适用于第二个示例,但不适用于第一个示例;请参阅tempfile docs了解原因。