2015-01-16 78 views
0

我正在處理以字符分隔的十六進制文件,其中每個字段都有一個特定的起始代碼。我已經打開了文件'rb',但是我想知道,在使用.find獲得起始碼的索引後,如何從這個位置讀取一定數量的字節? 這是我如何加載文件和我所試圖做的Python讀取字符後的特定字節數

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

,其中7是我想從由find函數返回的索引讀取的字節數。我使用Python 2.7.3

+0

你能舉個例子嗎? – helloV

+0

你看到了什麼:'print(repr(open('your filename','rb')。read(10)))'? – jfs

+0

會讀取文件的前10個字節 – Jacksgrin

回答

1

你可以得到一個字符串的位置在一個字節串下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' 
>>> 
+0

非常感謝您的回覆。我確實提到這是一個給定的,但我想檢查,看看我是否做得對。首先,我正在閱讀二進制文件並存儲到一個filedata變量中,然後我正在查找我正在查找的字符,讓我們說'(G')。我沒有使用十六進制代碼(這會工作嗎?)和然後用索引在filedata變量上做一個子字符串 – Jacksgrin

+0

如果你已經把它作爲一個字節串(python2或python3,btw?),並且你已經找到了一個帶有pos = mybytestring.find(some_marker)的位置,那麼爲什麼不使用'mybytestring [pos:pos + bytes_to_read]'? –

+0

因爲我不確定數字是否放入字節中來讀取字符或字節,也不知道是否搜索實際字符而不是用作起始位置的字節代碼將起作用......是否? – Jacksgrin