简体   繁体   English

如何制作仅在基础文件的一部分上运行的文件对象?

[英]How do I make a file object that operates on only part of the underlying file?

I have a binary file consisting of an N-byte header, followed by a data block. 我有一个二进制文件,由一个N字节的标头和一个数据块组成。 I have input describing the locations of various bits of data, as offsets from the start of the data block; 我输入了描述数据各个位的位置的信息,以相对于数据块开头的偏移量进行描述; ie not the start of the file itself. 不是文件本身的开始。

I want to open the file in such a way that seek() calls (and anything similar) seek within the data block, not the whole file. 我想以这样的方式打开文件:在数据块中而不是整个文件中进行seek()调用(以及类似的操作)。

Some options I've considered: 我考虑过的一些选择:

  1. mmap . mmap Close, but its offset argument is limited to multiples of pagesize. 关闭,但其offset参数限制为pagesize的倍数。
  2. Subclass file objects and override seek() to add the header length. 子类文件对象并重写seek()以添加标头长度。 Google suggests this may be annoying to do right. Google认为这样做可能很烦人。
  3. Slurp the whole file minus the header, then make a bytesio. 将整个文件减去标题,然后制作一个bytesio。 Problematic if the file is huge. 如果文件很大,则有问题。
  4. Patch seek() on the opened file object. 在打开的文件对象上修补seek() I think this might work but monkeypatching makes me nervous. 我认为这可能有效,但是猴子修补让我感到紧张。

I think what I really want is something that looks and acts like a file object but only "sees" a portion of the underlying file. 我认为我真正想要的是外观和行为类似于文件对象,但仅“看到”基础文件的一部分的东西。 Is there a good way to do that? 有什么好办法吗?

Rather than inheritance and monkey-patching, you forgot a simpler option: implement a file-like class which seeks the way you want. 而不是继承和猴子修补,您忘记了一个更简单的选择:实现一个类似文件的类,该类将查找您想要的方式。 Then you'll have full control and non-leaky encapsulation. 然后,您将具有完全控制权和非泄漏封装。

mmap整个文件,然后使用一个memoryview的数据块你有兴趣,然后偏移到存储器视图将是相对于所述数据块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM