【问题标题】:How can i open a .zip file in python?如何在 python 中打开 .zip 文件?
【发布时间】:2017-10-17 18:01:46
【问题描述】:

为了打开 .zip 文件而不是 .gz,我必须在此代码中进行哪些更改?

import gzip
embeddingsIn = gzip.open(embeddingsPath, "r") if embeddingsPath.endswith('.gz') else open(embeddingsPath, encoding="utf8")

【问题讨论】:

  • 到目前为止你尝试过什么?您已使用zipfile 标签标记了这个问题,这恰好是您将使用的 Python 模块的名称。也许阅读该模块的文档?
  • 对不起,我已经删除了那个标签,实际上我是 python 新手,所以我对语法一无所知..
  • 好吧,开始here

标签: python zip gzip


【解决方案1】:

根据gzip documentation,没有简单或直接的方法可以做到这一点:

GzipFile 类读取和写入 gzip 格式的文件,[...] 请注意,该模块不支持 gzip 和 gunzip 程序可以解压缩的其他文件格式,例如 compress 和 pack 生成的文件格式。

一种可能的解决方法是使用zipfile module,它确实支持.zip 文件,并组合了一个自定义my_open 函数来打开.gz.zip 和通用文件

import zipfile, gzip

def my_open(path):
    if zipfile.is_zipfile(path):
        return zipfile.ZipFile(path)
    elif path.endswith('.gz'):
        return gzip.GzipFile(path)
    else:
        return open(path, encoding="utf8")

作为说明,我使用了 ZipFileGzipFile 构造函数,因为根据它们各自的文档(zipfilegzipfile),它们在功能上都等同于 gzip.open,而 @ 中没有实现987654333@.

【讨论】:

  • 感谢您的回复,您能否指导我如何将生成的文件传递给上面提到的变量 embeddingsIn。
  • 应该像embeddingsIn = my_open("path/to/file")一样简单
  • 非常感谢它必须解决问题。现在我得到了另一个与 embeddingsIn 中的 line 变量相关的错误:TypeError: 'ZipFile' object is not iterable 我会想办法的
猜你喜欢
  • 2014-11-07
  • 2023-04-03
  • 2022-01-26
  • 1970-01-01
  • 2014-01-03
  • 2021-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多