How do I save an image from a URL to a zipfile? For example I am trying to save this image to a zipfile but it keeps throwing the error "File not found".
What am I doing wrong?
from zipfile import ZipFile
from tempfile import TempFile
import urllib.request
with TemporaryFile() as tf:
with ZipFile(tf, mode='w') as zf:
image_url = 'https://upload.wikimedia.org/wikipedia/commons/a/ab/Wurmseegurke.jpg'
url = urllib.request.open(image_url)
filename = image_url.split('/')[-1]
zf.write(filename, url.read())
Here is the full error: FileNotFoundError: [Errno 2] No such file or directory: 'Wurmseegurke.jpg'
The TemporaryFile
get deleted after it is closed, so your image wont be available after it was written into it. You need to use writestr() to create a 'file object' in the zip:
from zipfile import ZipFile
import urllib.request
import os
image_url = 'https://upload.wikimedia.org/wikipedia/commons/a/ab/Wurmseegurke.jpg'
url = urllib.request.urlopen(image_url)
filename = image_url.split('/')[-1]
zipPath = '/tmp/%s.zip' % filename
with ZipFile(zipPath, mode='w') as zf:
zf.writestr(filename, url.read())
print(os.path.exists(zipPath)) # probing a zip file was written!
Output:
True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.