无法在 python 中写入二进制文件

Can't write binary file in python

我需要在 python 中编写一个二进制文件,其中前几行是 8 字节整数,其余是一堆双精度数字。我如何最好地做到这一点?我尝试了这段代码,但我被卡住了,因为出于某种原因,尽管在 wb 中打开,这段代码只生成 个文本文件。

if binary:
            outfile = open(filename,"wb")
            text = f"1\n8\n{nrcells}\n{nrspecs}\n"
            outfile.write(text.encode(encoding="UTF-8"))
            if self.rho.ndim == 3:
                for x3 in range(self.par["rho_dim"][2]):
                    for x2 in range(self.par["rho_dim"][1]):
                        text="\n".join(f"{d:.8e}" for d in self.rho[:, x2, x3]*10**(-10))+"\n"
                        outfile.write(text.encode(encoding="UTF-8"))

如果要写入二进制数据,仅以二进制模式打开文件是不够的。

当你执行这些行时

text = f"1\n8\n{nrcells}\n{nrspecs}\n"
outfile.write(text.encode(encoding="UTF-8"))

您仍在向其中写入文本数据。

相反,您可能想看看 struct and array 标准库模块。它们使您能够将数字数据写入 bytes objects 或二进制模式的文件。

要编写您的 1, 8, nrcells, nrspecs header,假设它们是 8 字节整数,您将执行如下操作:

# q means "long long", or 8 bytes signed integer
header_bytes_content = struct.pack('qqqq', 1, 8, nrcells, nrspecs)  
outfile.write(header_bytes_content)

要写你的浮点值,你可以一个一个地写:

# d means 8 byte floating point; f means 4 byte floating point
float_bytes_content = struct.pack('d', float_value)
outfile.write(float_bytes_content)

或者将所有值收集到一个数组中并将它们写入文件:

float_array = array.array('d', float_values)
float_array.tofile(outfile)

要从文件中读回,您可以使用 struct.unpackarray.fromfile

请注意,如果您不需要文件是二进制的,您可能不应该使用二进制格式。文本格式更易于代码和人类阅读和编写,通常不会占用太多空间 space.