python - 我如何知道 .npz 文件是否已压缩?

标签 python numpy python-zipfile

给定一个来自 np.saveznp.savez_compressed 的 .npz 文件,当它被 np.load 加载时,是否有任何如何检查文件是否被压缩?

我试着看看 docsGitHub 。它没有告诉我任何内容,只是告诉我文件是如何压缩的。

最佳答案

np.load 返回一个 NpzFile 对象。

  • 它有一个 zip attribute这是 ZipFile对象。

  • 其中有 infolist()返回 ZipInfo 列表的方法对象。

  • 其中有一个 compress_type 属性,其中包含所使用的压缩方法。

如果使用np.savez,则压缩类型为ZIP_STORED ,如果使用np.savez_compressed,则压缩类型为ZIP_DEFLATED (relevant source code)。

总结一下:

import numpy
import zipfile

def is_compressed(npz_file):
    zip_infos = npz_file.zip.infolist()
    if len(zip_infos) == 0:
        raise RuntimeError("Did not find ZipInfos unexpectedly")
    compress_type = zip_infos[0].compress_type
    if compress_type == zipfile.ZIP_STORED:
        return False
    elif compress_type == zipfile.ZIP_DEFLATED:
        return True
    else:
        raise ValueError("Unexpected compression type")

# Example
a = numpy.array([1, 2, 3])
numpy.savez("uncompressed.npz", a)
numpy.savez_compressed("compressed.npz", a)
u = numpy.load("uncompressed.npz")
c = numpy.load("compressed.npz")
print(is_compressed(u))  # False
print(is_compressed(c))  # True

关于python - 我如何知道 .npz 文件是否已压缩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76720601/

相关文章:

python - 多次调用后更改内部函数中的非局部变量的结果

python - numpy中两个一维向量的点积

python - 测试二维 numpy 数组中的成员资格

Python 在压缩大文件时使用 ZIP64 扩展名

python - 如何使用 zipfile 将多个 DataFrame 打包到一个文件中

python - 将数据点分组到系列中

python - 自适应卡 : How to create table with 6 columns without truncating text?

python - 用列表理解替换循环,而不是循环获取函数以在列表理解中返回新数组

python - 在 CSV 中写入时定位 numpy 矩阵和数组

python: zipfile.ZipFile 没有这样的文件或目录