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

标签 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 

欢迎任何想法。

最佳答案

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

一般来说,打开文件对象最好用with语句:

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

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

如果你不能使用 with 语句(我认为一些旧的 Python 版本不支持它与文件对象一起使用)你可以在你之后调用对象上的 close()完成:

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

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

关于python - 如果在下载时更改名称,则无法识别 .ZIP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13400811/

相关文章:

java - 使用 Apache Arrow 读取 Parquet 文件

android - Android ImageView 和 Progressbar 实现中的图像下载

iOS “Add to Home Screen” - 文件下载将用户踢出

python - 如何在 python3 中创建带有错误消息和状态代码的自定义异常

python - 组ID根据它们在pandas面板中各自的值

python - 如何分组和更新 Pandas 的值(value)?

Firefox 插件下载.jsm

python - Google App Engine 中的 KindError

python - 如何在不考虑额外列的情况下保留每个类别的最早记录?

python - 如何以编程方式创建 Google Cloud 存储访问 token python