今天在用python处理一个sEMG二进制数据的时候卡壳了好久,原文件是某程序生成的非标准数据文件,在第50个字节处有一个double数据需要读取;在200个字节后都是int32型的数据,9个一组
用Matlab处理的话很方便:
[code lang=”matlab”]fid = fopen(filename,’r’);%open the file
fseek(fid,50,’bof’);%50 OFFSET
chan = fread(fid,1,’double’);%get a double
fseek(fid,200,’bof’);%200 OFFSET from the beginning
data =fread(fid,[9 inf],’int32′);%save as 9XN matrix with int32 elements in it
fclose(fid);[/code]
用Python处理时遇到问题:
python自带的read()函数没有‘int32’或者‘double’这样的解码功能,例如
[code lang=”python”]fid = open(filename,’r’)%open the file
fid.seek(50)%50 OFFSET
chanstr = fid.read(8)%get 8 bytes[/code]
此时如果print chanstr的话(以该数为9.0为例),终端给出的将为
[code]’\x00\x00\x00\x00\x00\x00"@'[/code]
与此类似,int32亦无法直接获取。
经搜索,发现numpy库里的fromstring及fromfile可以解决该问题,代码如下:
[code lang=”python”]import numpy
fid = open(filename,’r’)
fid.seek(50)
chanstr = fid.read(8)
chan = numpy.fromstring(chanstr,dtype=numpy.double, count=1)
data_raw = numpy.fromfile(filename, dtype=numpy.int32)
data = data_raw[50:]
data.shape = chan, data.size/chan[/code]
记录备忘。