本篇介紹 Python 讀取二進制檔的方法,
以下 Python 讀取 binary 檔的方法將分為這幾部份,
- Python 讀取二進制檔的基本用法
- Python 使用
struct.unpack()
讀取二進制檔的 str 字串 - Python 使用
struct.unpack()
讀取二進制檔的 int 整數 - Python 使用
struct.unpack()
讀取二進制檔的多種資料
Python 讀取二進制檔的基本用法
在 Python 3 讀取二進制的範例如下,讀二進制檔時 open()
開檔模式要使用 'rb'
,跟 Python 2 不同的是 Python 3 讀進來的是 bytes 類別,而 Python 2 讀進來的是字元,以下示範Python 讀取 binary 檔的寫法,假設這個 binary 檔叫做 xxx.bin
,binary 檔案名稱你可以取任何名字,但通常我們不使用 .txt
作為副檔名,以免混淆,
1 | #!/usr/bin/env python3 |
讀取一個內容為 hello 的二進制檔的結果如下,
1 | <class 'bytes'> |
怎麼寫入可以看這篇。
我們可以將上述範例改寫成用十六進制方式印出來,
1 | #!/usr/bin/env python3 |
讀取一個內容為 hello
的二進制檔的結果如下,
1 | 0x68 0x65 0x6c 0x6c 0x6f |
Python 使用 struct.unpack()
讀取二進制檔的 str 字串
這邊介紹 Python 使用 struct.unpack()
讀取二進制檔的 str 字串,Python 只提供 read 與 write 函式寫入,並沒有提供對二進制讀取與寫入的函式,但是可以透過 struct 模組來達成這件事,以下範例是從二進制檔讀取長度 11 的字串,要注意的是 struct.unpack()
回傳的變數類型是 tuple,
1 | #!/usr/bin/env python3 |
讀取一個內容為 hello world
的二進制檔的結果如下,
1 | <class 'bytes'> |
因為 struct.unpack()
回傳的變數類型是 tuple,所以回傳變數只有一個的話需要這樣寫,
1 | (b,) = struct.unpack('11s', f.read()) |
struct.unpack()
回傳多個變數的用法的話可以這樣寫,
1 | #!/usr/bin/env python3 |
結果輸出如下,
1 | hello |
Python 使用 struct.unpack()
讀取二進制檔的 int 整數
這邊介紹 Python 使用 struct.unpack()
讀取二進制檔的 int 整數,從二進制檔裡讀取 int,要注意的是 struct.unpack()
回傳的變數類型是 tuple,
1 | #!/usr/bin/env python3 |
讀取一個內容為 123
的二進制檔的結果如下,
1 | 123 |
因為 struct.unpack()
回傳的變數類型是 tuple,所以回傳變數只有一個的話需要這樣寫,
1 | (num,) = struct.unpack('i', f.read()) |
怎麼寫入可以看這篇。
Python 使用 struct.unpack()
讀取二進制檔的多種資料
這邊介紹 Python 使用 struct.unpack()
讀取二進制檔的多種資料,如果我們要 Python 使用 struct.unpack()
讀取多種資料型態的話,可以這樣寫,假設我要讀取一個整數 123、一個浮點數 45.67,一個短整數 89,
1 | (a,b,c) = struct.unpack('ifh', f.read()) |
那麼將這些多種類型資料利用 struct.unpack()
從二進制檔讀取,就會是像這樣寫,
1 | #!/usr/bin/env python3 |
結果輸出如下,
1 | 123 |
剛剛是數字混合類型的範例,這次我們加入字串會是怎樣寫呢?
假設我要讀取一個字串 hello
、一個整數 12、一個浮點數 34.56、一個字串 python
,
1 | (a,b,c,d) = struct.unpack('5sif6s', f.read()) |
那麼將這些多種類型資料利用 struct.unpack()
從二進制檔讀取,就會像下範例這樣寫,
1 | #!/usr/bin/env python3 |
結果輸出如下,要將 bytes 轉換成字串的話可以用 decode()
,
1 | b'hello' |
怎麼寫入可以看這篇。
以上就是 Python 讀取二進制檔介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!
其他參考
python - Reading binary file and looping over each byte - Stack Overflow
https://stackoverflow.com/questions/1035340/reading-binary-file-and-looping-over-each-byte
https://www.delftstack.com/zh-tw/howto/python/read-binary-files-in-python/
其它相關文章推薦
Python 新手入門教學懶人包