Skip to main content
 首页 » 编程设计

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

2025年05月04日39lautakyan007

尝试将用 Fortran 生成的二进制文件读入 Python,其中包含一些整数、一些实数和逻辑数。目前我正确阅读了前几个数字:

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

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

请您参考如下方法:

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

另一种常见情况是各种值的短 header 后跟一堆同类类型的数据。

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

读取数据类型的常规模式

例如,你可能有这样的东西:

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

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

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

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

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

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

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

读入标题

另一种常见情况是,您有一个格式已知的 header ,然后是一长串常规数据。您仍然可以为此使用 np.fromfile,但您需要单独解析 header 。

首先,阅读标题。您可以通过几种不同的方式来做到这一点(例如,除了 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))