'How to add a bunch of images to a zipfile

I have a list of image filenames with about 150 entries. Every image is downloaded via urllib and stored on the system. The result is a zipfile containing several broken images. The last part of some images is missing / corrupt.

The image download works perfectly. Every image in the list is completely downloaded and a valid image. It looks like i have to wait until zf.write() is completely done until the next image is added. Is there a way to ensure this?

images = ['image-01.jpg', 'image-02.jpg', 'image-03.jpg']

zf = zipfile.ZipFile('file.zip', mode='w')

for image in images:

    download_url = 'http://foo/bar/' + image

    image_file = open(image, 'wb')
    image_file.write(urllib.urlopen(download_url).read())
    image_file.close

    zf.write(image)

zf.close()


Solution 1:[1]

Thanks to alecxe. The solution is to close the file correctly.

image_file.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stefan Antonelli