簡體   English   中英

python遍歷沒有行的二進制文件

[英]python iterate through binary file without lines

我在二進制文件中有一些數據需要解析。 數據被分成22個字節的塊,因此我試圖生成一個元組列表,每個元組包含22個值。 該文件雖然沒有分成幾行,所以在確定如何遍歷文件和獲取數據時遇到了問題。

如果我這樣做,那就很好了:

nextList = f.read(22)
newList = struct.unpack("BBBBBBBBBBBBBBBBBBBBBB", nextList)

其中newList包含22個值的元組。 但是,如果我嘗試對迭代的函數應用類似的邏輯,則會崩潰。

def getAllData():
    listOfAll = []
    nextList = f.read(22)
    while nextList != "":
        listOfAll.append(struct.unpack("BBBBBBBBBBBBBBBBBBBBBB", nextList))
        nextList = f.read(22)
    return listOfAll

data = getAllData()

給我這個錯誤:

Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
data = getAllData()
File "<pyshell#26>", line 5, in getAllData
listOfAll.append(struct.unpack("BBBBBBBBBBBBBBBBBBBBBB", nextList))
struct.error: unpack requires a bytes object of length 22

我是python的新手,所以我不太確定我在哪里出錯。 我肯定知道文件中的數據平均分為22個字節,因此這不是問題。

由於您報告說len(nextList) == 0時它正在運行,這可能是因為nextList (不是列表。)是一個空字節對象,它不等於一個空字符串對象:

>>> b"" == ""
False

所以你的狀況

while nextList != "":

即使nextList為空,也永遠不會為真。 這就是為什么使用len(nextList) != 22作為中斷條件的原因,甚至

while nextList:

應該足夠了。

不能保證read(22)返回長度為22的字符串。它的約定是返回長度在0到22(含)之間的字符串。 長度為零的字符串表示沒有更多數據要讀取。 在python 3文件對象產生bytes對象,而不是str strbytes永遠不會被視為相等。

如果您的文件很小,那么最好將整個文件讀入內存,然后將其拆分為大塊。 例如。

listOfAll = []
data = f.read()
for i in range(0, len(data), 22):
   t = struct.unpack("BBBBBBBBBBBBBBBBBBBBBB", data[i:i+22])
   listOfAll.append(t)

否則,您將需要做一些更復雜的事情來檢查從讀取中獲取的數據量。

def dataiter(f, chunksize=22, buffersize=4096):
    data = b''
    while True:
        newdata = f.read(buffersize)    
        if not newdata: # end of file
            if not data:
                return
            else:
                yield data 
                # or raise error  as 0 < len(data) < chunksize
                # or pad with zeros to chunksize
                return

        data += newdata
        i = 0
        while len(data) - i >= chunksize:
            yield data[i:i+chunksize]
            i += chunksize

        try:
            data = data[i:] # keep remainder of unused data
        except IndexError:
            data = b'' # all data was used

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM