【问题标题】:Python Read Certain Number of Bytes After CharacterPython在字符后读取一定数量的字节
【发布时间】:2015-01-16 19:19:01
【问题描述】:

我正在处理一个字符分隔的十六进制文件,其中每个字段都有一个特定的起始码。我已将文件打开为“rb”,但我想知道,在使用 .find 获取起始码的索引后,如何从该位置读取一定数量的字节? 这就是我加载文件的方式以及我正在尝试做的事情

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

其中 7 是我想从 find 函数返回的索引中读取的字节数。我正在使用 python 2.7.3

【问题讨论】:

  • 你能举个例子吗?
  • 你看到了什么:print(repr(open('your filename', 'rb').read(10)))
  • 将读取文件的前 10 个字节
  • 是的,它会的。你看到了什么? “十六进制文件”这个短语是可疑的——它可能表明您对文件是什么的根本误解(从应用程序的角度来看)。
  • 是否要在文件中查找字节序列bytearray([40, 71])(两个字节)?或者您想查找 text u'\u0028\u0047'(两个字符(两个 Unicode 代码点))?您应该知道在后一种情况下用于将文本存储在文件中的字符编码

标签: python parsing hex offset


【解决方案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'
>>> 

【讨论】:

  • 非常感谢您的回复。我确实提到这是给定的,但我想检查一下我是否做得对。首先,我正在读取二进制文件并将其存储到文件数据变量中,然后我正在查找我正在寻找的字符,可以说'(G'。我没有为此使用十六进制代码(这会工作吗?)和然后使用索引在 filedata 变量上做一个子字符串。
  • 如果您已经将它作为字节串(python2 或 python3,顺便说一句?)并且您找到了pos = mybytestring.find(some_marker) 的位置,那么为什么不使用mybytestring[pos:pos+bytes_to_read]
  • 因为我不确定以字节为单位读取的数字是否会读取字符或字节。也不知道搜索实际字符而不是用作起始位置的字节码是否可行……会吗?
  • 这一切都取决于您使用的是哪个版本的python,如果它不是字节串,您是否正确编码了“字符串”。也许您可以将此信息添加到您的原始帖子中,以便我们可以让 cmets 进行澄清。
  • @ Oliver -- 抱歉,我已添加信息以进行澄清。抱歉,我仍在努力获得良好的帖子结构。
猜你喜欢
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多