如果下载时名称发生更改,则无法识别.ZIP

时间:2012-11-15 15:34:28

标签: python python-3.x download zip unzip

我使用Python 3.3编写了一个下载和解压缩.zip文件的脚本。如果.zip的名称保持不变,这没有问题。如果我尝试在下载时更改.zip的名称,那么zipfile.is_zipfile()将无法将该文件识别为.zip文件[虽然它仍然在WinRAR中解压缩]。

我通过传递shutil.copyfileobj()不同的fdst名称(不是整个路径)来更改名称。

使用的下载代码是:

import urllib.request
import shutil
import os, os.path



def mjd_downloader(url, destdir, destfilename=None):

    req = urllib.request.Request(url)
    response = urllib.request.urlopen(req)

    #if no filename passed by destfilename, retrieve filename from ulr
    if destfilename is None:
        #need to isolate the file name from the url & download to it
        filename = os.path.split(url)[1]

    else:
        #use given filename
        filename = destfilename


    #'Download': write the content of the downloaded file to the new file

    shutil.copyfileobj(response, open(os.path.join(destdir,filename), 'wb')) 

使用的解压缩代码是:

import zipfile
from zipfile import ZipFile
import os, os.path
import shutil

def mjd_unzipper(zippathname, outfilebasename=None):
    #outfilebasename is a name passed to the function if a new name for 
    #the content is requried   
    if zipfile.is_zipfile(zippathname) is True:
        zfileinst = ZipFile(zippathname, 'r')
        zfilepath = os.path.split(zippathname)[0]
        zlen = len(zfileinst.namelist())
        print("File path: ", zfilepath)

        if outfilebasename is not None:
            for filename in zfileinst.namelist():
                memtype = os.path.splitext(filename)[1]
                outfilename = os.path.join(outfilebasename + memtype)
                print("Extracting: ", filename, " - to: ", outfilename)
                #curzfile = zfileinst.read(filename)
                curzfile = zfileinst.open(filename)
                shutil.copyfileobj(curzfile, open(
                    os.path.join(zfilepath, outfilename), 'wb'))
        else:
            for i in range(zlen):
                extractfile = zfileinst.namelist()[i]
                memtype = os.path.splitext(extractfile)[1]
                zfileinst.extract(extractfile, path = zfilepath)

        zipfile.ZipFile.close(zfileinst)
    else:
        print("Is not a zipfile")
        pass 

欢迎任何想法。

1 个答案:

答案 0 :(得分:0)

我认为您的文件从未关闭:在下载脚本的第24行中,您打开了目标文件以写入二进制数据。只有当你在同一个文件上调用close()时才会将数据从内存中推送到文件中(还有一种方法可以在不关闭文件的情况下调用,但我现在不记得了)。

通常,最好使用with语句打开文件对象:

with open(os.path.join(destdir,filename), 'wb') as f:
    shutil.copyfileobj(response, f)

with语句与文件对象一起使用时,它会在块的末尾自动关闭它们,如果你break从块中出来,或者块被留给任何其他块reason(可能是导致解释器退出的未处理异常)。

如果您不能使用with语句(我认为某些较旧的Python版本不支持将其用于文件对象),您可以在完成后调用对象上的close(): / p>

f = open(os.path.join(destdir,filename), 'wb')
shutil.copyfileobj(response, f)
f.close()

我希望这是原因,因为那将是一个简单的解决方法!

相关问题