Python在Ch之后读取一定数量的字节

2024-10-01 13:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我处理的是一个字符分隔的十六进制文件,其中每个字段都有一个特定的开始代码。我以'rb'的格式打开了文件,但是我想知道,在我使用.find获取startcode的索引之后,如何从这个位置读取一定数量的字节? 这就是我加载文件的方式和我要做的

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

其中7是要从find函数返回的索引中读取的字节数。我使用的是python2.7.3


Tags: 文件代码数量字节格式with方式open
1条回答
网友
1楼 · 发布于 2024-10-01 13:27:19

在python2.7下,可以获得bytestring中子字符串的位置,如下所示:

>>> 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中,它可以不使用):

^{pr2}$

相关问题 更多 >