【问题标题】:How to extract a specific file from an archive donwloaded from internet using only memory如何仅使用内存从从 Internet 下载的存档中提取特定文件
【发布时间】:2019-02-09 16:14:23
【问题描述】:

我正在寻找一种方法来从包含多个文件的存档中提取特定文件(知道他的名字),而无需在硬盘驱动器上写入任何文件。

我尝试同时使用 StringIO 和 zipfile,但我只获得了整个存档,或者来自 Zipfile 的相同错误(打开需要另一个参数而不是 StringIo 对象)

需要的行为:

archive.zip #containing ex_file1.ext, ex_file2.ext, target.ext
extracted_file #the targeted unzipped file

archive.zip = getFileFromUrl("file_url")
extracted_file = extractFromArchive(archive.zip, target.ext)

到目前为止我已经尝试过:

import zipfile, requests

data = requests.get("file_url")                                 
zfile = StringIO.StringIO(zipfile.ZipFile(data.content))
needed_file = zfile.open("Needed file name", "r").read()

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    有一个内置库 zipfile,用于处理 zip 档案。

    https://docs.python.org/2/library/zipfile.html

    您可以列出存档中的文件:

    ZipFile.namelist()
    

    并提取一个子集:

    ZipFile.extract(member[, path[, pwd]])
    

    编辑: 这个问题有内存中的 zip 信息。 TLDR,Zipfile 确实适用于内存中类似文件的对象。

    Python in-memory zip library

    【讨论】:

    • 是否处理 stringIO 类型?
    • 我不确定 stringIO 类型是什么......这似乎是一个用于读取字符串缓冲区的库。我不确定 zipfile 是否支持内存中解压缩,您必须从文档开始进行一些研究。
    【解决方案2】:

    经过几个小时的测试,我终于找到了为什么我没有成功:

    我正在缓冲 zipfile 对象,而不是缓冲文件本身,然后将其作为 Zipfile 对象打开,这引发了类型错误。

    方法如下:

    import zipfile, requests
    
    data = requests.get(url)                                 # Getting the archive from the url
    zfile = zipfile.ZipFile(StringIO.StringIO(data.content)) # Opening it in an emulated file
    filenames = zfile.namelist()                             # Listing all files 
    for name in filesnames:
        if name == "Needed file name":                       # Verify the file is present
            needed_file = zfile.open(name, "r").read()       # Getting the needed file content
            break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      • 2012-07-05
      • 2012-08-03
      相关资源
      最近更新 更多