檔案與IO --讀寫位元組資料中的一些問題
阿新 • • 發佈:2020-10-09
問題:
讀寫二進位制檔案,比如圖片、檔案、視訊等
函式:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
讀取寫入模式:
使用模式為rb
或wb
的open()
函式來讀取或寫入二進位制資料。
#rb:使用decode進行解碼讀取:'rb'/str.decode()
with open('somefile.bin','rb')as f: data=f.read() print(data) #b'testcontent' type:<class 'bytes'> print(data.decode('utf-8'))#testcontent 讀取檔案指定utf-8解碼data資料
#wb:b'str'位元組檔案直接寫入 這裡涉及str to byte
with open('somefile.bin','ab') as f:
data=b'hello_word'
f.write(data)
# testcontenthello_world
#wb:使用encode進行編碼寫入 'wb'/ str.encode()
with open('somefile.bin','ab') as f:
data= '\n'+'starting'
f.write(data.encode('utf-8'))
'''
testcontenthello_world
starting
'''
注意:
with open('somefile.bin','rb',encoding='utf-8')as f:
編碼報錯 binary mode doesn't take an encoding argument#rb操作時不支援指定encoding引數;
同樣wb也沒有
special
二進位制I/O還有一個鮮為人知的特性就是陣列和C結構體型別能直接被寫入,而不需要中間轉換為自己物件
#array模組 https://www.cnblogs.com/yescarf/p/13787181.html
#通過array直接寫入二進位制陣列
In [55]: import array
In [56]: nums=array.array('i',[0,0,0,1,0])
In [57]: with open('data.bin','wb') as f:
...: f.write(nums)
In [58]: with open('data.bin','rb') as f:
...: print(f.read())
...:
很多物件還允許通過使用檔案物件的readinto()
方法直接讀取二進位制資料到其底層的記憶體中去。比如:
>>> import array >>> a = array.array('i', [0, 0, 0, 0, 0, 0, 0, 0]) >>> with open('data.bin', 'rb') as f: ... f.readinto(a) ... 16 >>> a array('i', [1, 2, 3, 4, 0, 0, 0, 0]) >>>