NAGARJUNA PALURU
NAGARJUNA PALURU

Reputation: 119

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

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.

Upvotes: 7

Views: 22326

Answers (2)

Eduard Stepanov
Eduard Stepanov

Reputation: 1283

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

Upvotes: 6

jan
jan

Reputation: 744

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.

Upvotes: 8

Related Questions