以下代码导致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)
答案 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了解原因。