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

如何在同一个文件中写入两种不同dtype类型的numpy数据?

实现方案

分两种场景处理:

  • 场景1:尚未生成原始grid.dat文件,直接生成带头部的目标文件
    这种方式效率最高,无需额外读写已有文件,直接按顺序写入头部、数据即可:
    import numpy as np
    
    # 构造头部4个i4类型数值
    header_arr = np.array([1, 720, 152, 129], dtype='i4')
    # 构造你原本要写入的f4类型Fortran序数组
    data_arr = np.asfortranarray([[x.T], [y.T], [z.T]], dtype='f4')
    
    # 按顺序写入文件
    with open('grid.dat', 'wb') as f:
        header_arr.tofile(f)
        data_arr.tofile(f)
    
  • 场景2:已经生成了原始grid.dat文件,需要给现有文件追加头部
    先读取原始文件的全部内容,再拼接头部重新写入即可,操作前建议先备份原始文件避免数据丢失:
    import numpy as np
    
    # 读取原始文件的所有f4类型数据
    raw_data = np.fromfile('grid.dat', dtype='f4')
    # 构造头部数组
    header_arr = np.array([1, 720, 152, 129], dtype='i4')
    
    # 覆盖写入新的带头部的文件
    with open('grid.dat', 'wb') as f:
        header_arr.tofile(f)
        raw_data.tofile(f)
    

效果验证

你可以用下面的代码验证写入结果是否符合要求:

# 读取前4个i4类型值
read_header = np.fromfile('grid.dat', dtype='i4', count=4)
print(read_header)  # 输出 [  1 720 152 129] 即符合要求

# 跳过头部16字节(4个i4每个占4字节)读取原数据
read_data = np.fromfile('grid.dat', dtype='f4', offset=16)
# 后续按你需要的形状reshape即可

内容的提问来源于stack exchange,提问作者Harpreet Singh Chhabra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:54:04