簡體   English   中英

Python:將int寫入二進制文件

[英]Python: Writing int to a binary file

我有一個計算偏移量(差異)的程序,然后使用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

有人可以建議解決問題嗎?

試試這個。

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')將允許您向文件追加更多的內容。

您應該使用內置的struct模塊。 而不是這個:

np.uint16(Current-Start)

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM