读取具有不同数据类型的二进制文件

问题描述 投票:1回答:1

尝试将Fortran中生成的二进制文件读取到Python中,该文件具有一些整数,一些实数和逻辑。 目前,我正确地阅读了前几个数字:

x = np.fromfile(filein, dtype=np.int32, count=-1)
firstint= x[1]
...

(np是numpy)。 但是下一项是合乎逻辑的。 后来又在整数和实数之后。 我该怎么做?

python numpy binary-data
1个回答
5
投票

通常,当您读取诸如此类的值时,它们处于常规模式(例如,类似C的结构数组)。

另一个常见情况是各种值的短标头,然后是一堆同类型的数据。

让我们先处理第一种情况。

以常规模式读取数据类型

例如,您可能会有类似的内容:

float, float, int, int, bool, float, float, int, int, bool, ...

如果是这样,您可以定义一个dtype以匹配类型的模式。 在上述情况下,它可能类似于:

dtype=[('a', float), ('b', float), ('c', int), ('d', int), ('e', bool)]

(注意:定义np.dtype('f8,f8,i8,i8,?')方法有很多 。例如,您也可以将其写为np.dtype('f8,f8,i8,i8,?') 。有关更多信息,请参见numpy.dtype的文档。 )

当您读入数组时,它将是带有命名字段的结构化数组。 如果需要,您以后可以将其拆分为单个数组。 (例如, series1 = data['a']具有上面定义的series1 = data['a']

这样的主要优点是从磁盘读取数据将非常快。 Numpy会简单地将所有内容读取到内存中,然后根据您指定的模式解释内存缓冲区。

缺点是结构化数组的行为与常规数组略有不同。 如果您不习惯它们,一开始它们可能会令人困惑。 要记住的关键部分是数组中的每个项目都是您指定的模式之一。 例如,对于我上面显示的内容, data[0]可能类似于(4.3, -1.2298, 200, 456, False)

阅读标题

另一个常见的情况是,您的标头具有已知格式,然后包含大量常规数据。 您仍然可以使用np.fromfile ,但是您需要单独解析标头。

首先,读入标题。 您可以通过几种不同的方式来执行此操作(例如,除了np.fromfile ,还可以np.fromfile struct模块,尽管两种方法都可以很好地满足您的目的)。

之后,将文件对象传递给fromfile ,文件的内部位置(即由f.seek控制的位置)将位于标头的末尾和数据的开头。 如果文件的其余所有部分都是同类型的数组,则只需对np.fromfile(f, dtype)进行一次调用。

举个简单的例子,您可能会遇到以下情况:

import numpy as np

# Let's say we have a file with a 512 byte header, the 
# first 16 bytes of which are the width and height 
# stored as big-endian 64-bit integers.  The rest of the
# "main" data array is stored as little-endian 32-bit floats

with open('data.dat', 'r') as f:
    width, height = np.fromfile(f, dtype='>i8', count=2)
    # Seek to the end of the header and ignore the rest of it
    f.seek(512)
    data = np.fromfile(f, dtype=np.float32)

# Presumably we'd want to reshape the data into a 2D array:
data = data.reshape((height, width))
© www.soinside.com 2019 - 2024. All rights reserved.