Joseph
Joseph

Reputation: 351

zipping files generated on the fly

how can you zip a bunch of files generated on the "fly"?

im testing with this small scale scenerio:

from time import strftime
import zipfile

# create new file
today = strftime("%Y-%m-%d %H:%M:%S")

new_file = open('testing123.txt', 'w')
text = 'this file was just added:' + str(today)
new_file.write(text)

# create zip file and write to it
newZip = zipfile.ZipFile("test.zip", "w")
newZip.write('testing123.txt')
new_file.close()

print "file created"

two things, first the testing123.txt which is created at the top of the script is blank when you unzip the zip file created, and this should include a list of files that are generated in a loop.

so im wondering what the best approach to generate a bunch of files on the fly and then zip them all nicely to a zip folder.

Upvotes: 1

Views: 2142

Answers (1)

nneonneo
nneonneo

Reputation: 179422

First, the reason why the file appears empty after unzipping is that you did not close your text file after using it. Because you didn't close the file, your write was not actually committed to disk, so ZipFile.write saw an empty file. You can use with to automatically close the file when you're done with it, so you never have to forget .close:

with open('testing123.txt', 'w') as new_file:
    new_file.write('this file was just added:' + str(today))

(You could also use .flush() to force the write to be committed, but that's less common).

Second, if you're generating file contents programmatically, then you should use .writestr to write a string without creating an actual file on disk:

newZip = zipfile.ZipFile("test.zip", "w")
newZip.writestr('testing123.txt', 'this file was just added:' + str(today))
newZip.close()

Upvotes: 3

Related Questions