从Python中的文件中提取所需的字节

时间:2014-08-20 12:23:23

标签: python numpy binary scipy

我这里有一个二进制文件: ftp://n5eil01u.ecs.nsidc.org/SAN/GLAS/GLA06.034/2003.02.21/GLA06_634_1102_001_0079_3_01_0001.DAT

我必须从该文件中提取以下数据:

Byte Offset: 176 
Data type: 4-byte (long) integer
Total bytes: 160

我尝试如下:

import numpy as np    
fname = 'GLA06_634_1102_001_0079_3_01_0001.DAT' 

with open(fname,'rb') as fi:
    fi.seek (176,0)
    data= np.fromfile(fi,dtype='long',count=160)
    print data

没有成功,我的想法出了什么问题?

1 个答案:

答案 0 :(得分:0)

使用硬编码偏移量是一种相当脆弱的解决方案。但假设你知道自己在做什么:

Byte Offset: 176 
Data type: 4-byte (long) integer
Total bytes: 160

AKAICT,导致160/4 = 40 值读取(你能确认吗?)

此外,该类型应该是numpy定义类型之一。这里np.int32可能是正确的:

data= np.fromfile(fi,dtype=np.int32,count=40)

在我的电脑上,这会产生以下结果:

[1919251297  997485633 1634494218 1936678771 1634885475  825124212
  808333629  808464432  942813232 1818692155 1868526433 1918854003
 1600484449 1702125924  842871086  758329392  841822768 1728723760
 1601397100 1600353135 1702125938 1835627615 1026633317  809119792
  808466992 1668483643 1668509535 1952543327 1026633317  960048688
  960051513  909654073  926037812 1668483643 1668509535 1952543327
 1633967973  825124212  808464957  842018099]

如果这不符合预期,那么您可能会遇到endianness的问题。

Numpy支持custom defined types来解决这个问题:

例如:

  • np.dtype('<i4')是4个字节(带符号)整数 little endian
  • np.dtype('>i4')是4个字节(带符号)整数 big endian

在你的情况下,为了强制读取数据为小端,你可以写:

dt = np.dtype('<i4')

with open(fname,'rb') as fi:
    fi.seek (176,0)
    data= np.fromfile(fi,dtype=dt,count=40)
    print data