5.1 二進位數據
在 Python 中處理二進位文件有點不同於處理 純文本文件,因為二進位文件包含的數據格式不是給人看的。而是處理字節。
要處理二進位文件,使用 open() 函數並指定帶有字母 'b' 的模式(例如,'rb' 用於讀取, 'wb' 用於寫入等等)。
開啟二進位文件的例子:
- 讀取:
'rb' - 寫入:
'wb' - 添加:
'ab' - 讀取寫入:
'r+b','w+b','a+b'
範例:
file = open('example.bin', 'rb')
content = file.read()
print(content)
file.close()
變數 'content' 會包含字節數組。
二進位數據(字節)是最基礎的數據表示層級。任何數據都可以以二進位方式讀取。
這意味著,文本文件永遠可以作為二進位文件讀取, 但不是所有的二進位文件都可以被解釋為文本。
5.2 讀取二進位文件
讀取文件的全部內容
方法read() 以字節形式讀取文件的全部內容。
範例:
file = open('example.bin', 'rb')
content = file.read()
print(content)
file.close()
讀取特定數量的字節
方法read(n) 讀取文件中的 n 字節。
範例:
file = open('example.bin', 'rb')
content = file.read(10) # 讀取前10個字節
print(content)
file.close()
逐行讀取
方法 readline() 讀取文件中的一行。對於二進位文件,一行結尾是新行字元 (\n)。
範例:
file = open('example.bin', 'rb')
line = file.readline()
print(line)
file.close()
讀取所有行
方法 readlines() 讀取文件中的所有行並返回字節列表。
範例:
file = open('example.bin', 'rb')
lines = file.readlines()
for line in lines:
print(line)
file.close()
如果文件不含文本,比如壓縮包、圖片或者影片,則使用字符串方法可能無法正確工作。
5.3 寫入二進位數據
方法 write() 將字節寫入文件。要寫入的數據必須是字節 (bytes)。
讀取與寫入圖片
從文件中讀取圖片並將其寫入另一個文件。
# 讀取圖片
with open('input_image.jpg', 'rb') as infile:
image_data = infile.read()
# 寫入圖片
with open('output_image.jpg', 'wb') as outfile:
outfile.write(image_data)
還可以寫入文本數據:
範例:
data = b"Hello, World!"
lines = [b"First line.\n", b"Second line.\n", b"Third line.\n"]
file = open('example.bin', 'wb')
file.write(data)
file.writelines(lines)
file.close()
GO TO FULL VERSION