Iván Castro Iván Castro - 2 months ago 6
Python Question

How to add url file to zip

I have a zip file with the following structure:

my_zip.zip
|-file1.txt
|-folder1/
|-file2.txt


I want to add
some_file
from url to the
folder1
. 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
    some_file
    to that specific
    folder1
    ?

  • Should I download the
    some_file
    to my PC and next use
    z.write('path/to_my/local/some_file')
    ? There is no way to do it directly from url to the zip?


Answer

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