- 1 1. 簡介
- 2 2. Python 中讀取二進位檔案的方法與基本操作
- 3 3. 使用 Python 的二进制文件的有效读取方法
- 4 4. Python的二進位資料解析方法
- 5 5. 在 Python 中寫入二進位檔案
- 6 6. Python 處理二進位檔案的實作範例
- 7 7. 處理二進位元檔案時的注意事項與最佳實踐
- 8 8. 常見問題(FAQ)
1. 簡介
Python 不僅支援文字檔,還支援二進位檔的讀寫。透過處理二進位檔,可操作圖片、音訊、影片、壓縮檔等各種資料。本文將說明如何使用 Python 安全且高效地讀取二進位檔。
1.1 什麼是二進位檔?
二進位檔是指不是人類直接可讀的文字列,而是由電腦可理解的二進位資料(0 與 1 的組合)構成的檔案。以下列出常見的二進位檔案範例。
- 圖片檔案(PNG, JPEG, BMP 等)
- 音訊檔案(WAV, MP3, AAC 等)
- 影片檔案(MP4, AVI, MOV 等)
- 壓縮檔案(ZIP, RAR, GZ 等)
- 程式執行檔(EXE, DLL, BIN 等)
二進位檔大多在一般文字編輯器中開啟時會出現「文字亂碼」。這是因為資料以特定格式編碼,若未使用適當的程式解析,無法得到有意義的資訊。
1.2 與文字檔的差異
二進位檔與文字檔的主要差異在於其資料的儲存方式。
| 種類 | 資料內容 | 範例 |
|---|---|---|
| 文字檔 | 使用字元編碼儲存(UTF-8, Shift-JIS 等) | .txt, .csv, .json |
| 二進位檔 | 以 0 與 1 的位元組列儲存 | .jpg, .mp3, .exe |
主要差異
- 資料結構
- 文字檔僅包含可作為文字解釋的資料。
- 二進位檔則可包含各種資料(圖片、音訊、可執行程式碼等)。
- 大小
- 若儲存的資料較少,文字檔的檔案大小會較小。
- 即使內容相同,二進位檔因編碼因素可能會較大。
- 編輯方式
- 文字檔可使用
Notepad或VS Code等編輯器直接開啟編輯。 - 二進位檔必須使用專用程式(例如:二進位編輯器)才能編輯。
1.3 為何在 Python 中處理二進位檔
使用 Python 操作二進位檔的理由包括以下幾點。
① 圖片與音訊資料的處理
讀取二進位檔後,可在 Python 程式中解析圖片與處理音訊資料。
# Example: Read a PNG image file as binary
with open("image.png", "rb") as file:
binary_data = file.read()
print(binary_data[:20]) # Display the first 20 bytes② 壓縮資料的解析
Python 具備 zipfile 與 gzip 等模組,可對 ZIP 檔與 GZ 檔進行程式化的解壓縮與壓縮。
import gzip
# Example: Open a GZ-compressed file
with gzip.open("example.gz", "rb") as file:
content = file.read()
print(content)③ 二進位協定的解析
在網路通訊或資料庫的低階操作中,需要解析二進位資料。使用 struct 模組,可將二進位資料轉換為數值或字串。
import struct
# Example: Convert binary data to an integer
binary_data = b'x01x00x00x00' # 4-byte data
integer_value = struct.unpack('<I', binary_data)[0]
print(integer_value) # Output: 11.4 小結
- 二進位檔是用於保存圖片、音訊、壓縮資料等資訊的檔案格式。
- 與文字檔不同,資料以 0 與 1 的位元組列儲存。
- 使用 Python 可解析二進位資料,並進行處理與轉換。
- 透過 Python 的
open()函式與struct模組,可有效處理二進位檔。
2. Python 中讀取二進位檔案的方法與基本操作
在 Python 中,open() 函式可以用來開啟並讀取二進位檔案。本節將說明在 Python 中二進位檔案的基本操作方法。
2.1 使用 open() 函式讀取二進位檔案
Python 的 open() 函式是用來開啟檔案的基本函式。若要開啟二進位檔案,請指定 'rb'(唯讀二進位模式)。
基本語法
file = open("example.bin", "rb") # 'rb' means "read in binary mode"
binary_data = file.read() # Read the contents of the file
file.close() # Close the file然而,若未明確呼叫 close(),檔案將不會關閉,可能成為 資源洩漏的原因。因此,在 Python 中,通常使用 with 陳述式來安全地開啟檔案。
2.2 使用 with 陳述式安全地讀取二進位檔案
使用 with 陳述式時,檔案會自動關閉,即使發生錯誤也能適當釋放資源。
範例:安全讀取二進位資料
with open("example.bin", "rb") as file:
binary_data = file.read()
# When leaving the with-block, the file is automatically closed使用 with 陳述式的優點
file.close()無需呼叫(會自動關閉)- 即使發生錯誤也不會產生資源洩漏
- 程式碼簡潔且可讀性提升
2.3 讀取方法的變體
Python 提供了多種讀取二進位檔案的方法,請依需求選擇適當的方式。
① 一次性讀取全部資料(read())
將二進位檔案的內容 全部載入記憶體 的方法。
with open("example.bin", "rb") as file:
binary_data = file.read() # Read all data at once優點
- 簡單且易於理解
- 對於小檔案而言效率高
缺點
- 對於大型檔案(數百 MB-GB 級別),可能會佔用大量記憶體
② 依指定的位元組數逐段讀取(read(n))
透過 將檔案分段讀取,適用於大容量檔案的處理。
with open("example.bin", "rb") as file:
chunk = file.read(1024) # Read 1024 bytes (1KB) at a time
while chunk:
print(chunk) # Process the read data
chunk = file.read(1024) # Read the next 1024 bytes優點
- 可降低記憶體消耗
- 即使是大型檔案也能有效率地處理
缺點
- 不適合一次性處理整個檔案的用途
③ 逐行讀取二進位資料(readline())
若二進位資料中包含換行,則可以逐行讀取。
with open("example.bin", "rb") as file:
line = file.readline() # Read one line at a time
while line:
print(line)
line = file.readline() # Read the next line用途
- 二進位日誌檔案 等,處理包含換行的二進位資料
注意事項
- 若無換行,全部會被視為一行,因此僅在適當的檔案中有效
2.4 使用 seek() 操作檔案位置
-VOID-36@@,可以從檔案的任意位置讀取資料。
seek() 的基本語法
file.seek(offset, whence)| 參數 | 說明 |
|---|---|
offset | Number of bytes to move |
whence | Reference point (0: start of file, 1: current position, 2: end of file) |
範例:從檔案中間讀取資料
with open("example.bin", "rb") as file:
file.seek(10) # Move to the 10th byte from the start
data = file.read(5) # Read 5 bytes
print(data)用途
- 取得檔案的標頭資訊
- 解析資料的特定部分
2.5 使用 tell() 取得目前的檔案位置
使用 tell() 方法時,可以取得目前的檔案位置(位元組偏移)。
範例:確認檔案位置
with open("example.bin", "rb") as file:
file.read(10) # Read 10 bytes
position = file.tell() # Get the current file position
print(f"Current position: {position} bytes")用途
- 確認已讀取檔案的程度
- 在檔案中途處理時的除錯
2.6 總結
- 在 Python 中開啟二進位檔案時,使用
'rb'模式 - 使用
with陳述式可以安全關閉檔案 - 一次性讀取全部資料 (
read()) 會大量消耗記憶體,對於大容量檔案請使用read(n) - 使用
seek()移動檔案的任意位置,並使用tell()取得目前的檔案位置
3. 使用 Python 的二进制文件的有效读取方法
在前一节中,介绍了打开二进制文件的基本方法。本节将详细说明高效读取二进制文件的方法。Python 中,可以使用多种方式读取二进制数据,依据用途选择合适的手法非常重要。
3.1 一次性读取二进制文件的全部数据(read())
要一次性读取二进制文件,使用 read() 方法。
基本语法
with open("example.bin", "rb") as file:
binary_data = file.read()优点
- 简洁直观
- 适用于小文件(数 MB 以下)
缺点
- 文件较大时(数百 MB 以上)会大量消耗内存
- 若内存不足,程序可能崩溃
实例
with open("sample.bin", "rb") as file:
binary_data = file.read()
print(len(binary_data)) # Display file size (in bytes)此方法在数 MB 规模的文件上可以顺利处理。
3.2 按指定字节数分块读取(read(n))
处理大容量二进制文件时,推荐使用考虑内存效率、按固定字节数分块读取的方法。
基本语法
with open("example.bin", "rb") as file:
chunk = file.read(1024) # Read 1024 bytes (1KB) at a time
while chunk:
print(chunk)
chunk = file.read(1024) # Read the next 1024 bytes优点
- 降低处理大容量文件时的内存负担
- 可进行流式处理
缺点
- 实时处理数据时需要额外的处理
实例
with open("large_file.bin", "rb") as file:
while True:
chunk = file.read(4096) # Read 4KB at a time
if not chunk:
break # Stop when no more data
print(f"Read {len(chunk)} bytes")使用此方法,即使是GB 级别的文件也能在不压迫内存的情况下处理。
3.3 按行读取二进制数据(readline())
如果二进制数据中包含换行符,则可以按行读取。
基本语法
with open("example.bin", "rb") as file:
line = file.readline()
while line:
print(line)
line = file.readline()用途
- 二进制日志文件 等,适用于处理包含换行的二进制数据
注意事项
- 如果二进制文件没有换行,则全部视为一行
- 在普通二进制数据处理时不常使用
3.4 从文件的特定位置读取数据(活用 seek())
在解析二进制文件时,需要从文件的特定位置读取数据的情况会出现。这时可以活用 seek() 方法。
基本语法
file.seek(offset, whence)| 参数 | 说明 |
|---|---|
offset | Number of bytes to move |
whence | Reference point (0: start of file, 1: current position, 2: end of file) |
实例:从特定位置读取数据
with open("example.bin", "rb") as file:
file.seek(10) # Move to the 10th byte from the start
data = file.read(5) # Read 5 bytes
print(data)使用此方法,可帮助文件头部的解析以及具有特定数据结构的文件处理。
3.5 获取文件的当前位址(tell())
使用 tell() 方法,可以获取当前文件位置(字节偏移)。
实例
with open("example.bin", "rb") as file:
file.read(20) # Read 20 bytes
position = file.tell() # Get the current file position
print(f"Current position: {position} bytes")用途
- 确认已读取文件的进度
- 在文件中途进行处理时的调试
3.6 使用内存映射文件高速读取(mmap)
使用 mmap 模块,可以将大容量二进制文件映射到虚拟内存,实现高速访问。
基本语法
import mmap
with open("example.bin", "rb") as file:
with mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as mmapped_file:
print(mmapped_file[:100]) # Get the first 100 bytes优点
- 因为可以在内存中处理整个文件,所以可以实现高速访问
- 可以直接访问特定范围
缺点
- 比 Python 标准文件处理稍微困难
- 映射过大的文件可能导致内存不足
3.7 总结
- 二进制文件的高效读取,需要根据文件大小和用途选择合适的方法
- 小文件使用
read()进行一次性读取 - 大文件使用
read(n)分块处理 - 要从文件的特定位置获取数据,活用
seek() - 使用
mmap可以实现高速数据访问,但需根据用途注意

4. Python的二進位資料解析方法
使用 Python,即可將二進位資料轉換為整數、浮點數、字串等有意義的資料型別。此處將以 struct 模組的使用方式為中心進行說明。
4.1 使用 struct 模組的解析
Python 的 struct 模組用於像 C 語言的結構體一樣解析與轉換二進位資料。
基本語法
import struct
value = struct.unpack(format, binary_data)| 格式字元 | 意義 | 位元組數 |
|---|---|---|
i | Signed integer | 4 |
I | Unsigned integer | 4 |
f | Float (IEEE 754) | 4 |
d | Double (IEEE 754) | 8 |
s | Byte string | 指定大小 |
例:讀取整數
import struct
# Binary data (4 bytes)
binary_data = b'x01x00x00x00' # 1 (little-endian)
# Unpack (unsigned int, little-endian)
value = struct.unpack('<I', binary_data)[0]
print(value) # Output: 1例:讀取字串
import struct
# 10-byte binary data
binary_data = b'HelloWorld'
# Interpret as string data
decoded_string = struct.unpack('10s', binary_data)[0].decode('utf-8')
print(decoded_string) # Output: HelloWorld例:讀取浮點數
import struct
# 4-byte float (IEEE 754 format)
binary_data = b'x00x00x80x3f' # Represents 1.0
# Unpack
value = struct.unpack('<f', binary_data)[0]
print(value) # Output: 1.04.2 位元組序的差異(大端序與小端序)
二進位資料的解讀會因 端序(位元組順序) 而異。
| 類型 | 特徵 |
|---|---|
| 小端序(Little Endian) | 從最低位元組開始依序儲存(在 Intel 系 CPU 中常見) |
| 大端序(Big Endian) | 從最高位元組開始依序儲存(在網路通訊中常用) |
例:確認端序的差異
import struct
binary_data = b'x01x00x00x00' # 1 (little-endian)
# Little-endian
little_endian = struct.unpack('<I', binary_data)[0]
print(f"Little Endian: {little_endian}") # Output: 1
# Big-endian
big_endian = struct.unpack('>I', binary_data)[0]
print(f"Big Endian: {big_endian}") # Output: 167772164.3 小結
- 使用
struct模組,即可將二進位資料轉換為整數、浮點數、字串等 - 需要注意端序的指定(
<Little Endian,>Big Endian) - 因檔案格式的端序可能不同,若未正確解讀會導致數值錯誤
5. 在 Python 中寫入二進位檔案
迄今為止,我們已說明了使用 Python 的二進位檔案的讀取方法。在此說明二進位檔案的寫入方法。Python 中,使用 'wb' 模式即可將資料寫入二進位檔案。
5.1 使用 open() 函式的基本寫入
使用 open() 函式指定 'wb' 模式時,檔案會以二進位寫入模式開啟。
基本語法
with open("example.bin", "wb") as file:
file.write(binary_data)要點
- 指定
'wb'模式時,既有內容會被覆寫 file.write()的參數必須是bytes型
5.2 寫入位元組列
在 Python 中,二進位資料會被視為 bytes 型。
範例:寫入位元組列
with open("output.bin", "wb") as file:
file.write(b'x01x02x03x04') # Write 4 bytes of data在此情況下,output.bin 會依序寫入稱為 01 02 03 04 的 4 位元組。
5.3 使用 struct.pack() 寫入二進位資料
使用 struct.pack(),即可將 Python 的數值或字串轉換為二進位資料並儲存至檔案。
範例:寫入整數
import struct
# Unsigned 16-bit int (H) and unsigned 32-bit int (I)
binary_data = struct.pack('<HI', 512, 123456789)
with open("numbers.bin", "wb") as file:
file.write(binary_data)範例:寫入字串
import struct
text = "Hello"
binary_data = struct.pack('10s', text.encode('utf-8')) # 10-byte fixed length
with open("text.bin", "wb") as file:
file.write(binary_data)範例:寫入浮點數
import struct
float_value = 3.14
binary_data = struct.pack('<f', float_value) # 4-byte float
with open("float.bin", "wb") as file:
file.write(binary_data)5.4 以追加模式寫入二進位
若要在檔案末端加入資料,請使用 'ab' 模式。
範例:追加模式
with open("output.bin", "ab") as file:
file.write(b'xffxff') # Append data執行此程式碼後,FF FF 會被加入至既有 output.bin 的末端。
5.5 替換檔案的一部
若要覆寫已存在檔案的一部,請使用 'r+b' 模式。
範例:在檔案中段寫入資料
with open("output.bin", "r+b") as file:
file.seek(10) # Move to the 10th byte
file.write(b'ª»') # Write 2 bytes of data在此情況下,檔案第 10 位元組起的 2 位元組會被寫入至 ª»。
5.6 小結
- 在 Python 中寫入二進位檔案時,使用
'wb'模式 - 使用
struct.pack(),即可將數值或字串轉換為二進位格式並儲存 - 使用
'ab'模式即可進行追加 - 使用
'r+b'模式即可替換既有檔案的一部
6. Python 處理二進位檔案的實作範例
到此為止,我們已學習了使用 Python 進行二進位檔案的基本讀寫方法。本節將介紹實際二進位檔案的解析與處理具體範例。
6.1 PNG 圖像的二進位解析
什麼是 PNG 檔案?
PNG(Portable Network Graphics)是一種壓縮格式的影像檔案,標頭資訊與影像資料皆以二進位資料儲存。
PNG 檔案的標頭結構
PNG 檔案的前 8 位元組是顯示檔案為 PNG 格式的魔術數字(89 50 4E 47 0D 0A 1A 0A)。
解析 PNG 的二進位資料
with open("example.png", "rb") as file:
header = file.read(8) # Get the first 8 bytes
print("PNG Header:", header)輸出範例
PNG Header: b'x89PNGrnx1an'透過確認此魔術數字,即可判斷該檔案是否為 PNG 格式。
6.2 WAV 音訊檔案的二進位解析
什麼是 WAV 檔案?
WAV(Waveform Audio File Format)是一種未壓縮的音訊格式,標頭中包含取樣率、聲道數、位元深度等資訊。
WAV 檔案的標頭解析
WAV 檔案使用 RIFF 格式,前 44 位元組儲存中介資訊。
解析 WAV 的二進位資料
import struct
with open("example.wav", "rb") as file:
header = file.read(44) # Get the first 44 bytes (WAV header)
# Parse RIFF header
riff, size, wave = struct.unpack('<4sI4s', header[:12])
# Parse format information
fmt, fmt_size, audio_format, num_channels, sample_rate = struct.unpack('<4sIHHI', header[12:24])
print(f"RIFF Header: {riff}")
print(f"Format: {wave}")
print(f"Audio Format: {audio_format}")
print(f"Channels: {num_channels}")
print(f"Sample Rate: {sample_rate} Hz")輸出範例
RIFF Header: b'RIFF'
Format: b'WAVE'
Audio Format: 1
Channels: 2
Sample Rate: 44100 Hz- RIFF → 表示為 WAV 格式的魔術數字
- Channels: 2 → 立體聲
- Sample Rate: 44100 Hz → CD 音質
6.3 自訂二進位格式的解析
部分檔案使用自訂的二進位格式。Python 可使用 struct 進行解析。
範例格式
| 位元組數 | 資料型別 | 內容 |
|---|---|---|
| 0–3 | I (4-byte integer) | File ID |
| 4–7 | f (4-byte float) | Version |
| 8–17 | 10s (10-byte string) | Name |
二進位資料的解析
import struct
with open("custom_data.bin", "rb") as file:
data = file.read()
file_id, version, name = struct.unpack('<If10s', data)
print(f"File ID: {file_id}")
print(f"Version: {version}")
print(f"Name: {name.decode().strip()}")輸出範例
File ID: 12345
Version: 1.2
Name: TestFile6.4 總結
- PNG 解析 → 以魔術數字確認格式
- WAV 解析 → 從標頭確認聲道數與取樣率
- 自訂格式 → 可使用
struct.unpack()抽取數值與字串
7. 處理二進位元檔案時的注意事項與最佳實踐
在 Python 處理二進位元檔案時,效能最佳化・防止資料損毀・確保安全性等,有幾項注意事項。在此,我們彙總二進位元檔案處理的最佳實踐。
7.1 優化大容量檔案的處理
二進位元檔案可能達到數百 MB 到數 GB。避免全讀取,改以區塊為單位處理較為安全。
NG範例:一次性讀取大容量檔案
with open("large_file.bin", "rb") as file:
data = file.read() # Load entire file into memory (dangerous)建議範例:以區塊為單位處理
with open("large_file.bin", "rb") as file:
while chunk := file.read(4096): # Read in 4KB chunks
process(chunk)7.2 with 語句安全關閉檔案
close() 忘記會導致資源洩漏的原因。請務必使用 with 語句。
NG範例
file = open("example.bin", "rb")
data = file.read()
# Forgot to close() → leak建議範例
with open("example.bin", "rb") as file:
data = file.read()
# File is closed automatically7.3 正確指定 Endian(Byte Order)
依環境或協定可能是Little Endian或Big Endian,若未正確指定會導致資料損壞。
| Endian | 特徵 |
|---|---|
| Little Endian | 低位元組在前(如 Intel CPU) |
| Big Endian | 高位元組在前(如網路協定等) |
範例:Endian 的差異
import struct
binary_data = b'x01x00x00x00'
value_le = struct.unpack('<I', binary_data)[0] # Little Endian
print("Little Endian:", value_le) # 1
value_be = struct.unpack('>I', binary_data)[0] # Big Endian
print("Big Endian:", value_be) # 167772167.4 以例外處理防止錯誤
檔案操作常伴隨錯誤。務必加入 try-except。
範例:安全的二進位元讀取
import struct
try:
with open("example.bin", "rb") as file:
binary_data = file.read(4)
value = struct.unpack('<I', binary_data)[0]
print(f"Value: {value}")
except FileNotFoundError:
print("Error: File not found.")
except struct.error:
print("Error: Invalid binary format.")
except Exception as e:
print(f"Unexpected error: {e}")7.5 二進位元資料的除錯方法
使用 binascii.hexlify() 或 Linux 的 hexdump 即可檢視二進位元內容。
在 Python 中以十六進位顯示
import binascii
with open("example.bin", "rb") as file:
binary_data = file.read(16)
print(binascii.hexlify(binary_data))在 Linux/macOS 上的檢查
hexdump -C example.bin | head7.6 總結
- 大容量檔案以區塊處理優化記憶體效率
- 使用
with語句確實關閉檔案 - Endian 錯誤會導致資料損毀
- 以例外處理安全處理錯誤
- 可使用
binascii.hexlify()或hexdump進行除錯
8. 常見問題(FAQ)
關於二進位檔案的讀寫與解析,彙整了許多人會疑問的重點,以 FAQ 形式呈現。說明使用 Python 處理二進位資料的一般問題與解決方案。
Q1: 文字檔與二進位檔的差異是什麼?
| 項目 | 文字檔 | 二進位檔 |
|---|---|---|
| 保存格式 | 文字編碼(UTF-8、Shift-JIS 等) | 0 與 1 的位元組列 |
| 副檔名範例 | .txt, .csv, .json | .jpg, .png, .mp3, .bin |
| 編輯方式 | 可直接在編輯器編輯 | 需要專用程式或二進位編輯器 |
| 用途 | 原始碼、設定檔 | 影像、音訊、影片、執行檔 |
Q2: 使用 Python 開啟二進位檔時,'rb' 與 'r' 的差異是什麼?
| 模式 | 說明 |
|---|---|
'r' | 文字模式。換行碼會自動轉換 |
'rb' | 二進位模式。換行碼不會轉換,直接處理 |
Q3: struct 模組的使用方式不清楚。該怎麼使用?
struct 模組用於將二進位資料轉換為數值或字串(unpack),或相反地進行二進位化(pack)。
範例:將二進位資料轉換為整數
import struct
binary_data = b'x01x00x00x00'
value = struct.unpack('<I', binary_data)[0] # Little Endian unsigned int
print(value) # 1Q4: 如何將二進位資料轉換為文字?
將其轉換為十六進位表示可提升可讀性。
import binascii
with open("example.bin", "rb") as file:
binary_data = file.read()
hex_data = binascii.hexlify(binary_data)
print(hex_data)Q5: Endian 是什麼?
Endian 指的是位元組的排列順序。
| 類型 | 說明 |
|---|---|
| Little Endian | 低位元組在前(如 Intel CPU 等) |
| Big Endian | 高位元組在前(如網路通訊等) |
Q6: 如何有效率地處理大型二進位檔?
建議使用以區塊(部分區段)方式讀取的方法。
with open("large_file.bin", "rb") as file:
while chunk := file.read(4096): # Read in 4KB chunks
process(chunk)Q7: 如何除錯二進位資料?
使用 Python 的 binascii.hexlify() 或 Linux 的 hexdump 命令。
在 Python 中確認
import binascii
with open("example.bin", "rb") as file:
binary_data = file.read(16)
print(binascii.hexlify(binary_data))在 Linux/macOS 中確認
hexdump -C example.bin | head總結
- 使用
'rb'模式開啟二進位 - 使用
struct進行 pack/unpack 以執行解析與寫入 - 正確指定 Endian 很重要
- 大型檔案使用區塊處理以提升效率
- 可使用
binascii.hexlify()或hexdump進行除錯
最後
至此,使用 Python 的二進位檔案讀寫與解析完整指南已完成。未來請在實際專案中應用,並嘗試更高階的處理 🚀




