写作和阅读数据

时间:2013-08-24 07:15:05

标签: python arrays python-2.7 file-io numpy

在我的bin文件中,数据排列为01 02 03 04。看完之后

data X = numpy.fromfile(   ,dtype=uint32)

X成为:

04 03 02 01... 

此外,当X01 02 03 04...类似并使用X.tofile()将其写入文件时,文件内容将变为04 03 02 01

我需要以这样的方式编写和加载数组,以便我可以按相同的顺序获取它们,关于问题可能是什么的任何想法?

1 个答案:

答案 0 :(得分:3)

你使用little-endian处理器,所以字节顺序不同,我不是一个笨拙的用户,但试试:

>>> hex(numpy.fromfile('1.txt', dtype=numpy.dtype('>u4')))
'0x1020304L'
>>>

顺便提一下,请查看更多Data type objects (dtype),数据没有变化,请参阅:

>>> # we stored 01 02 03 04
>>> numpy.uint32(0x01020304).tofile('1.txt')
>>>
>>> # we see 04 03 02 01
>>> open('1.txt', 'r').read()
'\x04\x03\x02\x01'
>>>
>>> # when you load it, it's the same data
>>> hex( numpy.fromfile('1.txt', dtype=numpy.uint32) )
'0x1020304L'
>>>
相关问题