Iván Castro Iván Castro - 1 year ago 96
Python Question

How to add url file to zip

I have a zip file with the following structure:


I want to add
from url to the
. I know that I can do something like:

>>> import zipfile
>>> z = zipfile.ZipFile("my_zip.zip", "w")
>>> z.write("some_file")

But, there are two issues:

  • How to add the
    to that specific

  • Should I download the
    to my PC and next use
    ? There is no way to do it directly from url to the zip?

Answer Source

Use ZipFile.writestr(arcname, data).

To write to a folder in the zipfile, you just write the foldername as if you were writing to a folder in a folder (So folder1/some_file).

import urllib.request
import zipfile

z = zipfile.ZipFile("my_zip.zip", "w")
page = urllib.request.urlopen('http://example.com/')  # Change to website
z.writestr('folder1/some_file', page.read())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download