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

lor*_*ori 1 python numpy binary-data

试图将Fortran中生成的二进制文件读入Python,它有一些整数,一些实数和逻辑.目前我正确地阅读了前几个数字:

x = np.fromfile(filein, dtype=np.int32, count=-1)
firstint= x[1]
...
Run Code Online (Sandbox Code Playgroud)

(np是numpy).但下一个项目是合乎逻辑的.后来又在实际上再次实施.我该怎么做?

Joe*_*ton 5

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

另一种常见的情况是各种值的短标题,然后是一堆同质类型的数据.

让我们先处理第一个案例.

阅读数据类型的常规模式

例如,您可能会遇到以下情况:

float, float, int, int, bool, float, float, int, int, bool, ...
Run Code Online (Sandbox Code Playgroud)

如果是这种情况,您可以定义一个dtype以匹配类型的模式.在上面的例子中,它可能看起来像:

dtype=[('a', float), ('b', float), ('c', int), ('d', int), ('e', bool)]
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

阅读标题

另一个常见的情况是,您有一个知道格式的标题,然后是一系列常规数据.你仍然可以使用np.fromfile它,但你需要单独解析标题.

首先,读入标题.您可以通过几种不同的方式执行此操作(例如struct,除了可以查看模块之外np.fromfile,尽管它们可能适用于您的目的).

之后,当您将文件对象传递给时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))
Run Code Online (Sandbox Code Playgroud)