如何在python中打开.zip文件?

时间:2017-10-17 18:01:46

标签: python zip gzip

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

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

1 个答案:

答案 0 :(得分:0)

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

  

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

可能的解决方法可能是使用zipfile module,它确实支持.zip个文件,并将自定义my_open函数放在一起以打开.gz,{{ 1}}和通用文件

.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") ZipFile构造函数,因为根据各自的文档(zipfilegzipfile),它们在功能上等同于{{ 1}},未在GzipFile中实现。

相关问题