問題
有二進制文件中保存了 20 億個 2 Bytes 的數,需將其讀出,每 20000 個數作圖,擬合后輸出結果。
解決
1 # -*- coding: utf-8 -*- 2 """ 3 @author: kurrrr 4 """ 5 6 import struct 7 8 def main(): 9 data_file = open('run0035.bin', 'rb') 10 data_temp = data_file.read(2) 11 data_short, = struct.unpack('h', data_temp) 12 print(data_short) 13 14 if __name__ == '__main__': 15 main()
- open 時加上 b 關鍵詞
- read() 函數實現讀取,參數為讀取的字節數
- 使用 struct 模塊中的 unpack() 函數將二進制轉化為十進制,注意 unpack() 函數返回的是 tuple,因此需要用 data_short, = struct.unpack(‘h’, data_temp)
- 關於 struct 模塊中的 format 具體可在官網上找到。