問題
有二進制文件中保存了 20 億個 2 Bytes 的數,需將其讀出,每 20000 個數作圖,擬合後輸出結果。
解決
# -*- coding: utf-8 -*- """ @author: kurrrr """ import struct def main(): data_file = open('run0035.bin', 'rb') data_temp = data_file.read(2) data_short, = struct.unpack('h', data_temp) print(data_short) if __name__ == '__main__': main()
總結
open 時加上 b 關鍵詞
read() 函數實現讀取,參數為讀取的字節數
使用 struct 模塊中的 unpack() 函數將二進制轉化為十進制,注意 unpack() 函數返回的是 tuple,因此需要用 data_short, = struct.unpack(‘h', data_temp)
關於 struct 模塊中的 format 具體可在官網上找到。
[kyec555 ] Python讀取二進制文件代碼方法解析已經有229次圍觀