Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to directly add file to zip in python?

Tags:

python

zip

I am new to python. Here my target is to put data into a file in zip. Following is the code I have written, in which I am write data to a unzipped_file, then writing unzipped_file in zipped_file.zip and then removing unzipped file.

import os
import zipfile

##Some code above.............
for some_data in big_data:
    with open('unzipped_file', 'a+') as unzipped_f:
        unzipped_f.write(some_data)

##Some code in between...........

with zipfile.ZipFile('zipped_file.zip', 'w') as zipped_f:
    zipped_f.write("unzipped_file")

os.remove("unzipped_file")

Instead of creating an intermediate unzipped_file. Can I directly write my data in zipped_file in one step.

like image 806
Eudie Avatar asked Nov 30 '16 10:11

Eudie


Video Answer


1 Answers

zipfile.writestr(file_name, bytes) writes raw data represented by bytes into an archive. file_name is the name of a file the archive will contain.

with zipfile.ZipFile('zipped_file.zip', 'w') as zipped_f:
    zipped_f.writestr("file_name", some_data)

EDIT: the only thing you can do to write multiple pieces of data to some file in an archive is to write all of it at once:

with zipfile.ZipFile('zipped_file.zip', 'w') as zipped_f:
    zipped_f.writestr("file_name", ''.join(x for x in big_data))

The method above will work only if big_data contains strings. Otherwise you could try pickle.dumps(big_data) or pickle.dumps(list(big_data)).

Note that then a copy of big_data (unless it's a generator) will be constructed in memory and then written to a file. It's impossible to update a file inside an existing ZipFile archive without extracting it and then zipping again.

like image 75
ForceBru Avatar answered Oct 07 '22 15:10

ForceBru