download a zip file to a local drive and extract all files to a destination folder using python 2.5

前端 未结 3 641
孤城傲影
孤城傲影 2021-01-01 07:40

I am trying to download a zip file to a local drive and extract all files to a destination folder.

so i have come up with solution but it is only to \"download\" a f

相关标签:
3条回答
  • 2021-01-01 07:57

    urllib.urlretrieve can get a file (zip or otherwise;-) from a URL to a given path.

    extractall is indeed new in 2.6, but in 2.5 you can use an explicit loop (get all names, open each name, etc). Do you need example code?

    So here's the general idea (needs more try/except if you want to give a nice error message in each and every case which could go wrong, of which, of course, there are a million variants -- I'm only using a couple of such cases as examples...):

    import os
    import urllib
    import zipfile
    
    def getunzipped(theurl, thedir):
      name = os.path.join(thedir, 'temp.zip')
      try:
        name, hdrs = urllib.urlretrieve(theurl, name)
      except IOError, e:
        print "Can't retrieve %r to %r: %s" % (theurl, thedir, e)
        return
      try:
        z = zipfile.ZipFile(name)
      except zipfile.error, e:
        print "Bad zipfile (from %r): %s" % (theurl, e)
        return
      for n in z.namelist():
        dest = os.path.join(thedir, n)
        destdir = os.path.dirname(dest)
        if not os.path.isdir(destdir):
          os.makedirs(destdir)
        data = z.read(n)
        f = open(dest, 'w')
        f.write(data)
        f.close()
      z.close()
      os.unlink(name)
    
    0 讨论(0)
  • 2021-01-01 08:21

    The shortest way i've found so far, is to use +alex answer, but with ZipFile.extractall() instead of the loop:

    from zipfile import ZipFile
    from urllib import urlretrieve
    from tempfile import mktemp
    
    filename = mktemp('.zip')
    destDir = mktemp()
    theurl = 'http://www.example.com/file.zip'
    name, hdrs = urlretrieve(theurl, filename)
    thefile=ZipFile(filename)
    thefile.extractall(destDir)
    thefile.close()
    
    0 讨论(0)
  • 2021-01-01 08:23

    For downloading, look at urllib:

    import urllib
    webFile = urllib.urlopen(url)
    

    For unzipping, use zipfile. See also this example.

    0 讨论(0)
提交回复
热议问题