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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With