【问题标题】:Read in Python compressed data in C, using zlib使用 zlib 在 C 中读取 Python 压缩数据
【发布时间】:2019-04-09 15:10:17
【问题描述】:

我有一个 C 代码,它为物理模拟编写了多个数据文件。这些数据文件基本上是包含值的 2d 映射的文本文件,范围从 -1 到 +1。它们可能很大(每个大约 100 Mb),但由于许多值通常是相同的(+1 或 -1 的长字符串),我认为压缩它们是个好主意。

编写文件的 C 代码的相关部分如下:

FILE *fp1;
char file1[] = "output_file.dat";
fp1 = fopen(file1,"w");
for ( i = 0; i < Nx; i++ ) {
    for ( j = 0; j < Ny; j++ ) {
        fprintf(fp1, "%.5f ", creal(phi[i*Ny+j]));
    }
    fprintf(fp1, "\n");
}
fclose(fp1);

读取文件的 Python 代码的相关部分是:

import numpy as np
data = np.loadtxt("output_file.dat")

现在,我正在尝试使用 zlib 库添加压缩。我通过以下方式更改了 C 代码:

# include <zlib.h>
gzFile fp1;
char file1[] = "output_file.dat";
fp1 = gzopen(file1,"w");
for ( i = 0; i < Nx; i++ ) {
    for ( j = 0; j < Ny; j++ ) {
        gzprintf(fp1, "%.5f ", creal(phi[i*Ny+j]));
    }
    gzprintf(fp1, "\n");
}
gzclose(fp1);

还有 Python 代码:

import numpy as np
import zlib
compressed_data = open("output_file.dat", 'rb').read() 
data = zlib.decompress(compressed_data)

C 代码似乎运行良好。正在写入数据文件,它们小于 2 Mb(考虑到内容的冗余,这是合理的)。不幸的是,Python 脚本给了我一个错误:

error: Error -3 while decompressing data: incorrect header check

任何人都可以指出我如何调试它的正确方向吗?谢谢!

【问题讨论】:

标签: python c numpy compression zlib


【解决方案1】:

好的,解决方案非常简单。基本上,如果我使用 .gz 扩展名编写数据文件:

# include <zlib.h>
gzFile fp1;
char file1[] = "output_file.gz";
fp1 = gzopen(file1,"w");
for ( i = 0; i < Nx; i++ ) {
    for ( j = 0; j < Ny; j++ ) {
        gzprintf(fp1, "%.5f ", creal(phi[i*Ny+j]));
    }
    gzprintf(fp1, "\n");
}
gzclose(fp1);

然后,我可以使用loadtext函数读取它们,它们会被numpy自动解压:

import numpy as np
data = np.loadtxt("output_file.gz")

或者,我仍然可以使用zlib.decompress 函数,但是再传递一个参数(如this 问题中所述):

zlib.decompress(compressed_data, 15 + 32)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多