0

我编写了一个小应用程序,当通过链接提供时下载一个 zip 文件(具有不同的扩展名)并将文件解压缩到重命名的文件夹中。出于某种原因,它适用于我的一些 zip 文件,但不适用于所有文件。

我得到一个:

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'

我的代码是:

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

我的工作下载文件:

蟒蛇下载_unzip.py“ http://dl.dropbox.com/u/2971439/dae.kmz

一个不工作的:

蟒蛇下载_unzip.py“ http://dl.dropbox.com/u/2971439/rally_car_youbeq.kmz

请注意,这两个文件都可以使用我的操作系统 (Ubuntu) 正确提取

4

1 回答 1

0

通过一些繁重的代码更改解决了我的问题:

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()
于 2013-02-25T11:25:26.950 回答