简体   繁体   English

Python 将图像从 URL 保存到 ZipFile

[英]Python Save Image from URL to ZipFile

How do I save an image from a URL to a zipfile?如何将图像从 URL 保存到 zipfile? For example I am trying to save this image to a zipfile but it keeps throwing the error "File not found".例如,我试图将此图像保存到 zipfile,但它不断抛出错误“找不到文件”。

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'这是完整的错误: 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. TemporaryFile在关闭后会被删除,因此您的图像在写入后将不可用。 You need to use writestr() to create a 'file object' in the zip:您需要使用 writestr() 在 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM