簡體   English   中英

Python在字符后讀取一定數量的字節

[英]Python Read Certain Number of Bytes After Character

我正在處理一個字符分隔的十六進制文件,其中每個字段都有一個特定的起始代碼。 我已將文件打開為“ rb”,但我想知道,在使用.find獲取啟動碼的索引之后,如何從該位置讀取一定數量的字節? 這就是我加載文件的方式以及我要嘗試執行的操作

with open(someFile, 'rb') as fileData:
    startIndex = fileData.find('(G')
    data = fileData[startIndex:7]

其中7是我想從find函數返回的索引中讀取的字節數。 我正在使用python 2.7.3

您可以像這樣在python2.7下獲取字節串中子字符串的位置:

>>> with open('student.txt', 'rb') as f:
...     data = f.read()
... 
>>> data  # holds the French word for student: élève
'\xc3\xa9l\xc3\xa8ve\n'
>>> len(data)  # this shows we are dealing with bytes here, because "élève\n" would be 6 characters long, had it been properly decoded!
8
>>> len(data.decode('utf-8'))
6
>>> data.find('\xa8')  # continue with the bytestring...
4
>>> bytes_to_read = 3
>>> data[4:4+bytes_to_read]  
'\xa8ve'

您可以查找特殊字符,並且為了與Python3k兼容,最好在字符前加上b ,以指示這些是字節(在Python2.x中,它可以正常工作):

 >>> data.find(b'è')  # in python2.x this works too (unfortunately, because it has lead to a lot of confusion): data.find('è')
3
>>> bytes_to_read = 3
>>> pos = data.find(b'è')
>>> data[pos:pos+bytes_to_read] # when you use the syntax 'n:m', it will read bytes in a bytestring
'\xc3\xa8v'
>>> 

暫無
暫無

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

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