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

2024-09-30 04:40:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python3.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')) 

使用的解压码是:

^{pr2}$

欢迎有任何想法。在


Tags: 文件thetopathimport名称urlos
1条回答
网友
1楼 · 发布于 2024-09-30 04:40:57

我从来没有为你的二进制文件的目的地打开你的文件。只有当您对同一个文件调用close()时,数据才会从内存推送到文件中(也有方法可以在不关闭文件的情况下调用,但我现在记不起来了)。在

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

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

with语句与file对象一起使用时,如果您曾经break离开块,或者由于任何其他原因(可能是导致解释器退出的未处理异常),它会在块的末尾自动关闭它们。在

如果您不能使用with语句(我想一些旧的Python版本不支持它与file对象一起使用),那么您可以在完成后对该对象调用close()

^{pr2}$

我希望这就是原因,因为那将是一个简单的修复!在

相关问题 更多 >

    热门问题