io.RawIOBase
的快速子類似乎有伎倆,至少在我的用例中。我明白這不是io.RawIOBase interface
的完整實施,但它完成了工作。
class Substream(io.RawIOBase):
"""Represents a view of a subset of a file like object"""
def __init__(self, file: io.RawIOBase, start, size):
self.file = file
self.start = start
self.size = size
self.p = 0
def seek(self, offset, origin=0):
if origin == 0:
self.p = offset
elif origin == 1:
self.p += offset
# TODO: origin == 2
else:
raise ValueError("Unexpected origin: {}".format(origin))
def read(self, n):
prev = self.file.tell()
self.file.seek(self.start + self.p)
data = self.file.read(n if self.p + n <= self.size else self.size - self.p)
self.p += len(data)
self.file.seek(prev)
return data
使用它像這樣
with open(filename) as f:
print(Substream(f, 10, 100).read(10))
我不知道這是否可以在文件描述符級別上進行,而不是莫名其妙......?