我有一個檔案,在運行file命令時有如下輸出:
#file test.bin。
#test.bin : data
#file -i test.bin
#test.bin: application/octet-stream; charset=binary。
我想讀取這個檔案的內容并轉發給一個接受這個讀資料為字串的Python庫。
file = open("test.bin"/span>, "rb"/span>)
readBytes = file.read() # python type : <class 'bytes' >
output = test.process(readBytes) # process期待一個字串。
我已經嘗試了str(readBytes),然而這并不奏效。我看到在檔案test.bin中也有不可列印的字串,因為strings test.bin的輸出遠遠小于檔案中存在的實際位元組數。
有什么方法可以將讀取的位元組轉換為字串嗎?還是我想實作一些根本沒有意義的目標?
uj5u.com熱心網友回復:
嘗試使用Bitstring。它是讀取位元的好包。
# import module。
from bitstring import ConstBitStream
# 讀取檔案 # 讀取檔案
x = ConstBitStream(filename='file.bin')
# 讀取5個位元
output = x.read(5)
#轉換為無符號int
int_val = output.uint
uj5u.com熱心網友回復:
你的意思是由?
output = test.process(readBytes.decode('latin1')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/307859.html
標籤:
