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

耗尽温柔 提交于 2019-12-31 03:41:06

问题


Using python zipfile module I created a zip file as follows:

s = StringIO()
zip_file = zipfile.ZipFile(s, "w")
zip_file.write('/local/my_files/my_file.txt')
s.seek(0)

and now, I want this zip_file to be saved in my file system at path /local/my_files/ as my_file.zip. Generally to save a noraml files I used the following flow:

with open(dest_file, 'w') as out_file:
    for line in in_file:
        out_file.write(line)

But, I think I can't achieve saving a zipfile with this. Can any one please help me in getting this done.


回答1:


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.




回答2:


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")


来源:https://stackoverflow.com/questions/37566679/how-to-save-created-zip-file-to-file-system-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!