如何将一堆图像添加到zipfile

时间:2015-06-04 22:06:37

标签: python urllib zipfile

我有一个包含大约150个条目的图像文件名列表。每个图像都通过urllib下载并存储在系统中。结果是包含多个损坏图像的zipfile。某些图像的最后一部分缺失/损坏。

图像下载效果很好。列表中的每个图像都已完全下载并且是有效图像。看起来我必须等到zf.write()完全完成,直到添加下一个图像。有没有办法确保这个?

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

1 个答案:

答案 0 :(得分:0)

感谢alecxe。解决方案是正确关闭文件。

image_file.close()