Python: Writing int to a binary file

筅森魡賤 提交于 2019-12-10 17:14:09

问题


I have a program which calculates the offset(difference) and then stores them in an 16 bit unsigned int using numPy and I want to store this int into a binary file as it is in binary form. i.e. if the value of offset is 05, I want the file to show "01010000 00000000", but not as a string. The code I have written is:

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)

there is some processing after f.read(lines) but thats sort of the idea. The code works fine as long as the offset is less than 127. As soon as the offset goes above 127, a 0xC2 appears in the file along with the binary data.

data in the file appears as follows (hex view, little indian): 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

Could someone suggest a solution to the problem?


回答1:


Try this.

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])

output: 4 type 'numpy.int16'

I Hope this is wha you are looking for. Works for n>127 But read and writes numpy arrays... binwrite=open('testint.in','ab') will let you append more ints to the file.




回答2:


You should use the built-in struct module. Instead of this:

np.uint16(Current-Start)

Try this:

struct.pack('H', Current-Start)


来源:https://stackoverflow.com/questions/37129257/python-writing-int-to-a-binary-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!