首先,在这个问题被标记为重复之前,我知道其他人也问过类似的问题,但似乎没有一个明确的解释。我试图将一个二进制文件读入一个2D数组(这里有很好的文档http://nsidc.org/data/docs/daac/nsidc0051_gsfc_seaice.gd.html)。在
头是一个300字节的数组。在
到目前为止,我有
import struct
with open("nt_197912_n07_v1.1_n.bin",mode='rb') as file:
filecontent = file.read()
x = struct.unpack("iiii",filecontent[:300])
引发字符串参数长度错误。在
阅读数据(简短回答)
在从头部(见下文)确定网格的大小(} 读取数据。在
n_rows
xn_cols
=448x304)之后,可以简单地使用^{'>u1'
指定数据的格式,在本例中,无符号大小为1字节的整数,是big-endian格式。在用
^{pr2}$matplotlib.pyplot
绘制此图extent=
选项只指定轴值,您可以将这些值更改为lat/lon(从头部解析).unpack()中的错误说明
从docs for ^{} :
您可以通过查看Format Characters部分来确定格式字符串(
fmt
)中指定的大小。在您在
struct.unpack("iiii",filecontent[:300])
中的fmt
指定了4个int类型(为了简单起见,您还可以使用4i
=iiii
),每个类型的大小为4,需要一个长度为16的字符串。在您的字符串(
filecontent[:300]
)的长度为300,而您的fmt
要求的字符串长度为16,因此出现错误。在.unpack()的用法示例
例如,在阅读您提供的文档时,我提取了前21*6字节,其格式如下:
有:
这将返回21个元素的元组。注意一些元素中的空白填充以满足6字节的要求。在
注意事项:
fmt
,"6s"*21
是一个字符串,其中6s
重复21 时代。每个格式字符6s
代表一个6字节的字符串 (见下文),这将与您的 文件。在filecontent[:126]
中的数字126
计算为6*21 = 126
。在s
(string)说明符,前面的数字会 not表示将格式字符重复6次 通常用于其他格式字符)。相反,它指定大小 在绳子上。s
表示1字节字符串,而6s
表示 一个6字节的字符串。在更广泛的标题读取解决方案(长)
因为二进制数据必须手动指定,所以在源代码中这样做可能很乏味。您可以考虑使用一些配置文件(如
.ini
文件)此函数将读取头并将其存储在字典中,其中的结构是从
.ini
文件中给定的下面是一个
.ini
文件的示例。键是存储数据时要使用的名称,值是一对逗号分隔的值,第一个是起始索引,第二个是结束索引。这些值取自您文档中的表1。此功能可以如下使用:
相关问题 更多 >
编程相关推荐