为什么 zipfile 模块 is_zipfile 函数无法检测到 gzip 文件?

Why zipfile module is_zipfile function cannot detech a gzip file?

我知道这个问题Why "is_zipfile" function of module "zipfile" always returns "false"?。我想寻求更多的澄清和确认。

我使用 gzip 模块在 python 中创建了一个 zip 文件。

如果我在 OSX 中使用 file 命令检查 zip 文件,我得到这个

>  file data.txt
data.txt: gzip compressed data, was "Slide1.html", last modified: Tue Oct 13 10:10:13 2015, max compression

我想编写一个通用函数来判断文件是否经过 gzip 压缩。

import gzip
import os

f = '/path/to/data.txt'
print os.path.exists(f)  # True

with gzip.GzipFile(f) as zf:  
    print zf.read()  # Print out content as expected

import zipfile

print zipfile.is_zipfile(f)  # Give me false.  Not expected

我想使用 zipfile 模块,但它总是报错。

我只想确认 zipfile 模块与 gzip 不兼容。如果是这样,为什么会这样? zipgzip 是否被视为不同的格式?

I have created a zip file in python using the gzip module.

不,你没有。 gzip 不创建 zip 文件。

I just want to have a confirmation that zipfile module is not compatible with gzip.

已确认。

If so, why it is the case?

gzip 文件是用 zlib 压缩的单个文件,header 非常小。一个 zip 文件是多个文件,每个文件都可以选择用 zlib 压缩,在一个带有 header 和目录的存档中。

Are zip and gzip considered different format?

是的。