【问题标题】:Python - Reading and Writing Structured Binary FilesPython - 读写结构化二进制文件
【发布时间】:2017-09-22 05:38:18
【问题描述】:

目前我正在尝试操作一种二进制文件, 什么样的结构是这样的:

FileHeader + [SectionHeader + Binary(1D-array)] * NumSetions

在网上搜索后,我想出了以下代码来阅读它:

import numpy as np

# Always BIG Endian
#file_header bytes: 12
file_header_dtype = np.dtype([
    ('nsection', '>i4'), # number of sections
    ('nsample', '>i4'), # number of samples for each section
    ('dt', '>f4'), # sampling rate
    ])

#section_header bytes: 28
section_header_dtype = np.dtype([
    ('rec', '>i4'), # record number
    ('x', '>f8'), # x, in meter
    ('y', '>f8'), # y, in meter
    ('z', '>f8'), # z, in meter
    ])

def dtype_section(nt):
    return np.dtype(section_header_dtype.descr + [('binary', ('>f4',nt))])

def read_file_header(_file):
    with open(_file, 'rb') as f:
        file_header = np.fromstring(f.read(12), dtype=file_header_dtype)
    return file_header

def readFile(filename):
    raw = open(filename, 'rb')
    file_header = np.fromstring(raw.read(12), dtype=file_header_dtype)
    nt = file_header['nsample'][0]
    dtype_file_sections = dtype_section(nt)
    data = np.fromstring(raw.read(), dtype=dtype_file_sections)
    return (file_header, data)

通过这种方式,我可以轻松调用带标头的二进制部分并执行plt.imshow 或其他任何操作。

data = readFile('site1.bin')
data_arr = data[1]['binary']
#plt.imshow(data_arr)

问题是,我找不到在保持相同数据结构的同时输出数据的方法

ndarray.tofile() 每次仅适用于一个数组

np.array((data[0],data[1])).tofile('test') 会导致 IOError

IOError: 无法以二进制模式将对象数组写入文件

我对 Python 还是很陌生,我不确定我是否犯了任何错误。 或者我应该考虑另一种方式来读取这种文件,而不是使用numpy.dtype? 请帮帮我。

【问题讨论】:

  • 您不应该将file_header['nsample'][0] 的结果传递给dtype_section(nt)吗?
  • 糟糕,我的错。让我纠正一下

标签: python arrays python-2.7 numpy binaryfiles


【解决方案1】:

直接的方法是简单地写入二进制文件:

with open('test','wb') as f:
    f.write(data[0].tobytes())
    f.write(data[1].tobytes())

【讨论】:

  • 我想你指的是numpy.ndarray.tobytes()。想到解决方案如此简单明了,我现在感到很尴尬......无论如何,谢谢你的回答。
  • @Pakox.Wang 是的,我的意思是tobytes(),对不起,有很多类似命名的方法:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多