Python:将int写入二进制文件

时间:2016-05-10 04:25:01

标签: python numpy file-writing

我有一个计算偏移量(差异)的程序,然后使用numPy将它们存储在16位无符号整数中,我想将这个int存储到二进制文件中,因为它是二进制形式。即如果offset的值是05,我希望文件显示“01010000 00000000”,但不是字符串。 我写的代码是:

target = open(file_cp, 'wb')
target.write('Entries')
target.write('\n')
Start = f.tell()
while(!EOF):
    f.read(lines)
    Current = f.tell()
    offset = np.uint16(Current-Start)
    target.write(offset)

在f.read(行)之后有一些处理,但这有点想法。只要偏移量小于127,代码就可以正常工作。一旦偏移量超过127,文件中就会出现0xC2和二进制数据。

文件中的数据如下所示(十六进制视图,小印度):     00 00 05 00 0e 00 17 00 20 00 3c 00 4e 00 7b 00 c2 8d 00 c2 92 00 c2 9f 00

有人可以建议解决问题吗?

2 个答案:

答案 0 :(得分:2)

试试这个。

import numpy as np
a=int(4)
binwrite=open('testint.in','wb')
np.array([a]).tofile(binwrite)
binwrite.close()

b=np.fromfile('testint.in',dtype=np.int16)
print b[0], type(b[0])

输出:4类型' numpy.int16'

我希望这是你在寻找的。 适用于n> 127 但读取和写入numpy数组... binwrite = open(' testint.in'' ab')会让你在文件中追加更多的内容。

答案 1 :(得分:0)

您应该使用内置的struct模块。而不是:

np.uint16(Current-Start)

试试这个:

struct.pack('H', Current-Start)
相关问题