0

i wrote a small app that downloads a zip file (with a different extension) when provided by a link and extracts the file to a renamed folder. For some reason its working for some of my zip files, but not for all of them.

I get a :

Traceback (most recent call last):
  File "download_unzip.py", line 48, in <module>
    main()
  File "download_unzip.py", line 42, in main
    shutil.move(unzip_file(temp_kmz),'temp_extracted/')
  File "download_unzip.py", line 26, in unzip_file
    fd = open(name, 'w')
IOError: [Errno 2] No such file or directory: 'models/model.dae'

My code is :

import sys , urllib , zipfile , os.path , argparse , shutil


parser = argparse.ArgumentParser(description="Download and Unzip")
parser.add_argument('url', help='The action to take (e.g. install, remove, etc.)')
args = parser.parse_args()

print args.url

url = args.url
temp_kmz="temp_kmz"

def unzip_file(path):
    zfile = zipfile.ZipFile(path)
    extracted_filename = zfile.infolist()[0].filename[:-1]

    for name in zfile.namelist():
        (dirname, filename) = os.path.split(name)
        #print "Decompressing " + filename + " on " + dirname
        if filename == '':
            # directory
            if not os.path.exists(dirname):
                os.mkdir(dirname)
        else:
            # file
            fd = open(name, 'w')
            fd.write(zfile.read(name))
            fd.close()
    zfile.close()

    return extracted_filename

def download_file():
    urllib.urlretrieve (url, temp_kmz)
    return True

def main():
    if (download_file()):
        print "Now deleting temp..."
        shutil.rmtree('temp_extracted/')
        print "unzipping.. and renaming folder"
        shutil.move(unzip_file(temp_kmz),'temp_extracted/')
        print "Finished!!"

    else:
        print "Error downloading file"

main()

my working downloaded file:

python download_unzip.py "http://dl.dropbox.com/u/2971439/dae.kmz"

The one that is not working:

python download_unzip.py "http://dl.dropbox.com/u/2971439/rally_car_youbeq.kmz"

Please note that both files extract properly with my OS (Ubuntu)

psychok7
  • 5,373
  • 9
  • 63
  • 101
  • 1
    I see many things wrong with your code. For starters, the `unzip_file()` function is passed the zip archive file name and attempts to extract _all_ the files from it but then only returns the name of the first one with the last character removed (so it's invalid which will cause the following `shutil.move()` call to fail). Also, please don't just say something "doesn't work". At the very least describe in detail how and include any traceback that occurred in your question. The basic idea is help us help you. – martineau Feb 23 '13 at 00:17
  • i take out the last character because it is a "/" and i thought it was best to remove it. Anyways it doesn't work even if i leave it. And about the traceback, if you see the first part of the code you'll see its there ;) – psychok7 Feb 25 '13 at 09:57
  • I would just unzip the file and use a path to read the folder if you need help with pathing click here>>>http://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7<< – Jordanian Dec 17 '13 at 19:30

1 Answers1

0

fixed my problem with some heavy code changes:

import urllib2 ,argparse, shutil, urlparse , os , zipfile, os.path
from zipfile import ZipFile as zip

parser = argparse.ArgumentParser(description="Download and Unzip")
parser.add_argument('url', help='The action to take (e.g. install, remove, etc.)')
args = parser.parse_args()

print args.url

url = args.url
temp_kmz="temp_kmz"

def extractAll(zipName):
    z = zip(zipName)
    for f in z.namelist():
        if f.endswith('/'):
            os.makedirs(f)
        else:
            z.extract(f)

def download(url, fileName=None):
    def getFileName(url,openUrl):
        if 'Content-Disposition' in openUrl.info():
            # If the response has Content-Disposition, try to get filename from it
            cd = dict(map(
                lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
                openUrl.info()['Content-Disposition'].split(';')))
            if 'filename' in cd:
                filename = cd['filename'].strip("\"'")
                if filename: return filename
        # if no filename was found above, parse it out of the final URL.
        return os.path.basename(urlparse.urlsplit(openUrl.url)[2])

    r = urllib2.urlopen(urllib2.Request(url))
    try:
        fileName = fileName or getFileName(url,r)
        with open(fileName, 'wb') as f:
            shutil.copyfileobj(r,f)
    finally:
        r.close()

def main():
    download(url,temp_kmz)
    extractAll(temp_kmz)
main()
psychok7
  • 5,373
  • 9
  • 63
  • 101