我有一组zip文件,其中包含几个ieee编码的二进制和文本文件。我使用了Pythons ZipFile模块,可以提取文本文件的内容
def readPropFile(myZipFile):
zf = zipfile.ZipFile(myZipFile,'r') # Open zip file for reading
zFileList=zf.namelist() # extract list of files embedded in _myZipFile_
# text files in _myZipFile_ contain the word 'properties' so
# get a list of the property files here
for f in zFileList:
if f.find('properties')>0:
propFileList.append(f)
# open first file in propFileList
pp2 = cStringIO.StringIO(zf.read(propFileList[0]))
fileLines = []
for ll in pp2:
fileLines.append(ll)
# return the lines in the property text file
return fileLines
现在除了读取二进制文件中的数据和创建一个浮点数组外,我还想做同样的事情。那么我该怎么做呢?在
二进制文件的格式是这样的,在matlabi中将它们解压到一个临时位置后,我可以用下面的代码读取它们
^{pr2}$我现在有一个简单的函数,尝试读取二进制数据
def readBinaryFile(myZipFile):
zFile = zipfile.ZipFile(myZipFile,'r')
dataFileName = 'dataFile.bin'
stringData = zFile.read(dataFileName)
ss=stringData[0:4]
data=struct.unpack('>f',ss)
但是我得到的值和MATLAB中报告的值一样。在
二进制文件中的第一个浮点
在问题的片段中,“属性文件”(不管是什么)是以一种相当松散的方式检测到的,当作为文本读取时,它们的内容中是否存在字符串“properties”。我不知道对于二进制ieeele文件来说,这是什么等价物。在
但是,对于Python,读取ieeele(或其他格式)文件的一个简单方法是使用SciPy's io.fopen模块。在
编辑
因为读取这样一个二进制文件需要知道它的结构,所以可以用结构包()格式如迈克尔·狄龙回应中所述!这只需要std库,而且同样简单!在
您也可以尝试Numpy扩展(here),它比SciPy轻一点。Numpy有很多I/O例程。例如
给你一个numpy数组。也许有一种不那么笨拙的方法来指定数据类型。在
你最需要的是这个答案How do I convert a Python float to a hexadecimal string in python 2.5? Nonworking solution attached
查看有关
struct.pack
的内容。在有关struct的更多详细信息,请参见Python docs
相关问题 更多 >
编程相关推荐