How to save created Zip file to file system in python?

三世轮回 提交于 2019-12-02 02:27:21
zip_file = zipfile.ZipFile("/local/my_files/my_file.zip", "w")
zip_file.write('/local/my_files/my_file.txt')
zip_file.close()

The first argument of the ZipFile object initialization is the path to which you want to save the zip file.

If you need to use StringIO, just try this code:

from StringIO import StringIO
import zipfile

s = StringIO()
with zipfile.ZipFile(s, "w", compression=zipfile.ZIP_DEFLATED) as zf:
    zf.write('/local/my_files/my_file.txt')

with open('/local/my_files/my_file.zip', 'wb') as f_out:
    f_out.write(s.getvalue())

Or you can do it in a simpler way:

import zipfile

with zipfile.ZipFile("/local/my_files/my_file.zip", "w", compression=zipfile.ZIP_DEFLATED) as zf:
    zf.write("/local/my_files/my_file.txt")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!