文章詳情頁(yè)
Python讀取二進(jìn)制文件代碼方法解析
瀏覽:7日期:2022-07-19 18:00:18
問題
有二進(jìn)制文件中保存了 20 億個(gè) 2 Bytes 的數(shù),需將其讀出,每 20000 個(gè)數(shù)作圖,擬合后輸出結(jié)果。
解決
# -*- coding: utf-8 -*-'''@author: kurrrr'''import structdef 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()
總結(jié)
open 時(shí)加上 b 關(guān)鍵詞 read() 函數(shù)實(shí)現(xiàn)讀取,參數(shù)為讀取的字節(jié)數(shù) 使用 struct 模塊中的 unpack() 函數(shù)將二進(jìn)制轉(zhuǎn)化為十進(jìn)制,注意 unpack() 函數(shù)返回的是 tuple,因此需要用 data_short, = struct.unpack(‘h’, data_temp)關(guān)于 struct 模塊中的 format 具體可在官網(wǎng)上找到。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
上一條:python算的上腳本語言嗎下一條:怎么快速自學(xué)python
相關(guān)文章:
排行榜
