我需要使用Python从大二进制文件中读取特定字节。使用f.seek()需要很长时间。是否有任何方法来获取文件的第一个字节的地址,然后添加地址以达到Python中的特定字节?
例如,给定一个包含asddfrgd
的文本文件
获取a的地址,添加5,然后获取结果值(即'r',假设每个字母有1个字节)。
你的描述不是很清楚。我假设你想在你的例子中获取"a"
之后的5个字节的所有值,这样"aardvark"
得到"a"
和"r"
并跳过最后的"a"
,因为添加5超出了字符串的结尾。
这是一个解决方案,它通过线性扫描文件而不是逐字节地跳过来返回这些值的列表:
def find_past(fn, which, step):
""" Read file 'fn' and return all elements 'step' bytes after
each occurrence of 'which'.
"""
f = open(fn, "rb")
n = 0 # current byte address
res = [] # list of result bytes
next = [] # list of next byte addresses to consider
while True:
c = f.read(1)
if c == "":
break
if next and next[0] == n:
res.append(c)
next.pop(0)
if c == which:
next.append(n + step)
n += 1
f.close()
return res
跟踪列表和字节偏移应该比f.seek()
便宜,但我没有在大数据上尝试过。