你可以得到一個字符串的位置在一個字節串下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'
>>>
你能舉個例子嗎? – helloV
你看到了什麼:'print(repr(open('your filename','rb')。read(10)))'? – jfs
會讀取文件的前10個字節 – Jacksgrin