我有一些用 Fortran77 编写的单精度小端无格式数据文件。我正在使用 Python 使用以下命令读取这些文件:
import numpy as np
original_data = np.dtype('float32')
f = open(file_name,'rb')
original_data = np.fromfile(f,dtype='float32',count=-1)
f.close()
在 Python 中进行一些数据操作后,我(试图)使用 Python 使用以下命令将它们写回原始格式:
out_file = open(output_file,"wb")
s = struct.pack('f'*len(manipulated_data), *manipulated_data)
out_file.write(s)
out_file.close()
但是好像不行。使用 Python 以原始的 fortran 未格式化格式写回数据的正确方法是什么?
问题详情:
我能够从 Fortran 读取带有操作数据的最终文件。但是,我想使用软件 (Paraview) 可视化这些数据。为此,我将未格式化的数据文件转换为 *h5 格式。我能够使用 h5 实用程序将原始数据和处理后的数据转换为 h5 格式。但是,虽然 Paraview 能够读取从原始数据创建的 *h5 文件,但 Paraview 无法读取从操作数据创建的 *h5 文件。我猜在翻译中丢失了一些东西。
这就是我用 Fortran(单精度数据)打开 Python 编写的文件的方式:
open (in_file_id,FILE=in_file,form='unformatted',access='direct',recl=4*n*n*n)
这是我用 Fortran 编写的原始无格式数据:
open(out_file_id,FILE=out_file,form="unformatted")
这些信息是否足够?
最佳答案
您是否尝试过使用操作数据数组的 .tofile 方法?它将以 C 顺序写入数组,但能够写入普通二进制文件。
.tofile 的文档还表明这与:
with open(outfile, 'wb') as fout:
fout.write(manipulated_data.tostring())
关于python - 用 Python 编写 Fortran 无格式文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14985311/