7

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.

2 Answers 2

8
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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.