簡體   English   中英

從二進制文件中刪除標題

[英]strip header from binary file

我有幾個演出的原始二進制文件,並且試圖將其分塊處理。 在開始處理數據之前,我必須刪除它具有的標頭。 由於原始的二進制文件格式,.find或檢查數據塊中的字符串之類的字符串方法均無效。 我想自動剝離標頭,但它的長度可能會有所變化,而我當前尋找最后一個換行符的方法不起作用,因為原始二進制數據的數據中有匹配的位。

Data format:
BEGIN_HEADER\r\n
header of various line count\r\n
HEADER_END\r\n raw data starts here

我如何閱讀文件

filename="binary_filename"
chunksize=1024
with open(filename, "rb") as f:
    chunk = f.read(chunksize)
    for index, byte in enumerate(chunk):
        if byte == ord('\n'):
            print("found one " + str(index))

有沒有一種簡單的方法可以提取HEADER_END \\ r \\ n行而無需在文件中滑動字節數組? 當前方法:

chunk = f.read(chunksize)
index=0
not_found=True
while not_found:
    if chunk[index:index+12] == b'HEADER_END\r\n':
        print("found")
        not_found=False
    index+=1

您可以使用線緩存:

import linecache
currentline = 0
while(linecache.getline("file.bin",currentline)!="HEADER_END\n"):
    currentline=currentline+1

#print raw data
currentline = currentline + 1
rawdata = linecache.getline("file.bin",currentline)
currentrawdata = rawdata
while(currentrawdata):
    currentrawdata = linecache.getline("file.bin",currentline+1)
    rawdata = rawdata + currentrawdata
    currentline = currentline + 1
print rawdata

更新

我們可以將問題分成兩部分,首先可以刪除標題,然后將其讀取為大塊:

lines= open('test_file.bin').readlines()
currentline = 0
while(lines[currentline] != "HEADER_END\r\n"):
     currentline=currentline+1
open('newfile.bin', 'w').writelines(lines[currentline:-1])

將創建一個僅包含原始數據的文件(newfile.bin)。 現在可以將其直接讀取成塊:

chunksize=1024
with open('newfile.bin', "rb") as f:
    chunk = f.read(chunksize)

更新2

也可以不使用中間文件來執行此操作:

#defines the size of the chunks
chunksize=20
filename= 'test_file.bin'
endHeaderTag = "HEADER_END\r\n"
#Identifies at which line there is HEADER_END
lines= open(filename).readlines()
currentline = 0
while(lines[currentline] != endHeaderTag):
     currentline=currentline+1
currentline=currentline+1
#Now currentline contains the index of the first line to the raw data

#With the reduce operation we generate a single string from the list of lines
#we are considering only the lines after the currentline
header_stripped = reduce(lambda x,y:x+y,lines[currentline:])

#Lastly we read successive chunks and we store them into the chunk list.
chunks = []
reminder = len(header_stripped)%chunksize
for i in range(1,len(header_stripped)/chunksize + reminder):
    chunks.append( header_stripped[(i-1)*chunksize:i*chunksize])

暫無
暫無

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

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