You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中读取并打印Fortran无格式文件的数据

在Python中读取Fortran无格式文件

需求:读取Fortran无格式文件,文件包含两个整数变量a、t,以及12个N×N×N维度的数组:d、g、s、r、Re、pr、scsx、ex、sy、ey、sz、ez。


方法一:使用scipy.io.FortranFile(推荐)

自动处理Fortran无格式文件的记录标记(每个记录首尾的长度标识),代码简洁易维护。

  1. 先安装scipy:pip install scipy
  2. 读取代码示例:
import numpy as np
from scipy.io import FortranFile

# 替换为实际维度N,若a/t代表N,可改为N = a
N = 10  

# 打开目标文件
with FortranFile('your_file.dat', 'r') as f:
    # 读取整数a和t,根据Fortran代码中的整数类型调整dtype(如np.int64)
    a = f.read_ints(dtype=np.int32)[0]
    t = f.read_ints(dtype=np.int32)[0]
    
    # 批量读取所有数组
    array_names = ['d', 'g', 's', 'r', 'Re', 'pr', 'scsx', 'ex', 'sy', 'ey', 'sz', 'ez']
    result = {}
    
    for name in array_names:
        # 读取数组并按Fortran列优先格式重塑,根据实际浮点类型调整dtype(如np.float32)
        array = f.read_reals(dtype=np.float64).reshape((N, N, N), order='F')
        result[name] = array

# 验证读取结果
print(f"a = {a}, t = {t}")
print(f"数组d的形状:{result['d'].shape}")

方法二:使用numpy.fromfile(无scipy依赖)

无需额外依赖,手动处理记录标记,适合环境受限场景:

import numpy as np

N = 10
# 匹配Fortran代码中的数据类型
dtype_int = np.int32
dtype_float = np.float64

with open('your_file.dat', 'rb') as f:
    # 读取整数a:跳过记录长度→读取a→跳过结尾长度
    _ = np.fromfile(f, dtype=dtype_int, count=1)
    a = np.fromfile(f, dtype=dtype_int, count=1)[0]
    _ = np.fromfile(f, dtype=dtype_int, count=1)
    
    # 读取整数t
    _ = np.fromfile(f, dtype=dtype_int, count=1)
    t = np.fromfile(f, dtype=dtype_int, count=1)[0]
    _ = np.fromfile(f, dtype=dtype_int, count=1)
    
    # 批量读取数组
    array_names = ['d', 'g', 's', 'r', 'Re', 'pr', 'scsx', 'ex', 'sy', 'ey', 'sz', 'ez']
    result = {}
    
    for name in array_names:
        _ = np.fromfile(f, dtype=dtype_int, count=1)
        # 读取N³个浮点元素,按列优先重塑数组
        array = np.fromfile(f, dtype=dtype_float, count=N*N*N).reshape((N, N, N), order='F')
        _ = np.fromfile(f, dtype=dtype_int, count=1)
        result[name] = array

关键注意事项

  • 数据类型匹配:必须保证Python中指定的dtype与Fortran代码中变量类型一致(如Fortran的integer对应np.int32,real*8对应np.float64),否则会读取错误。
  • 数组存储顺序:Fortran采用列优先存储,Python默认行优先,因此重塑数组时需指定order='F',避免维度混乱。
  • N值确定:如果a或t本身代表数组维度N,可直接将读取到的a或t赋值给N,无需手动指定。

内容的提问来源于stack exchange,提问作者Ajit Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:26:12