Python io.SEEK_CUR Examples

The following are 30 code examples for showing how to use io.SEEK_CUR(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module io , or try the search function .

Example 1
Project: qutebrowser   Author: qutebrowser   File: qtutils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
        self._check_open()
        self._check_random()
        if whence == io.SEEK_SET:
            ok = self.dev.seek(offset)
        elif whence == io.SEEK_CUR:
            ok = self.dev.seek(self.tell() + offset)
        elif whence == io.SEEK_END:
            ok = self.dev.seek(len(self) + offset)
        else:
            raise io.UnsupportedOperation("whence = {} is not "
                                          "supported!".format(whence))
        if not ok:
            raise QtOSError(self.dev, msg="seek failed!")

        return self.dev.pos() 
Example 2
Project: pyaaf2   Author: markreidvfx   File: cfb.py    License: MIT License 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        if whence == io.SEEK_CUR:
            offset = self.tell() + offset
        elif whence == io.SEEK_END:
            offset = self.dir.byte_size + offset
        if offset < 0:
            raise ValueError('New position is before the start of the stream')

        if offset > self.dir.byte_size:
            # logging.debug("overseek %d bytes, padding with zeros" % (offset - self.dir.byte_size))
            self.pos = self.dir.byte_size
            bytes_left = offset - self.dir.byte_size
            min_seek_size = self.storage.sector_size * 4
            while bytes_left:
                bytes_to_write = min(min_seek_size, offset - self.dir.byte_size)
                zeros = bytearray(bytes_to_write)
                self.write(zeros)
                bytes_left -= bytes_to_write

        self.pos = offset
        return offset 
Example 3
Project: teleport   Author: tp4a   File: IcnsImagePlugin.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, fobj):
        """
        fobj is a file-like object as an icns resource
        """
        # signature : (start, length)
        self.dct = dct = {}
        self.fobj = fobj
        sig, filesize = nextheader(fobj)
        if sig != b"icns":
            raise SyntaxError("not an icns file")
        i = HEADERSIZE
        while i < filesize:
            sig, blocksize = nextheader(fobj)
            if blocksize <= 0:
                raise SyntaxError("invalid block header")
            i += HEADERSIZE
            blocksize -= HEADERSIZE
            dct[sig] = (i, blocksize)
            fobj.seek(blocksize, io.SEEK_CUR)
            i += blocksize 
Example 4
Project: teleport   Author: tp4a   File: IcnsImagePlugin.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, fobj):
        """
        fobj is a file-like object as an icns resource
        """
        # signature : (start, length)
        self.dct = dct = {}
        self.fobj = fobj
        sig, filesize = nextheader(fobj)
        if sig != b"icns":
            raise SyntaxError("not an icns file")
        i = HEADERSIZE
        while i < filesize:
            sig, blocksize = nextheader(fobj)
            if blocksize <= 0:
                raise SyntaxError("invalid block header")
            i += HEADERSIZE
            blocksize -= HEADERSIZE
            dct[sig] = (i, blocksize)
            fobj.seek(blocksize, io.SEEK_CUR)
            i += blocksize 
Example 5
Project: python3_ios   Author: holzschu   File: IcnsImagePlugin.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, fobj):
        """
        fobj is a file-like object as an icns resource
        """
        # signature : (start, length)
        self.dct = dct = {}
        self.fobj = fobj
        sig, filesize = nextheader(fobj)
        if sig != b'icns':
            raise SyntaxError('not an icns file')
        i = HEADERSIZE
        while i < filesize:
            sig, blocksize = nextheader(fobj)
            if blocksize <= 0:
                raise SyntaxError('invalid block header')
            i += HEADERSIZE
            blocksize -= HEADERSIZE
            dct[sig] = (i, blocksize)
            fobj.seek(blocksize, io.SEEK_CUR)
            i += blocksize 
Example 6
Project: Fluid-Designer   Author: Microvellum   File: gzip.py    License: GNU General Public License v3.0 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        if self.mode == WRITE:
            if whence != io.SEEK_SET:
                if whence == io.SEEK_CUR:
                    offset = self.offset + offset
                else:
                    raise ValueError('Seek from end not supported')
            if offset < self.offset:
                raise OSError('Negative seek in write mode')
            count = offset - self.offset
            chunk = bytes(1024)
            for i in range(count // 1024):
                self.write(chunk)
            self.write(bytes(count % 1024))
        elif self.mode == READ:
            self._check_not_closed()
            return self._buffer.seek(offset, whence)

        return self.offset 
Example 7
Project: Imogen   Author: CedricGuillemet   File: gzip.py    License: MIT License 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        if self.mode == WRITE:
            if whence != io.SEEK_SET:
                if whence == io.SEEK_CUR:
                    offset = self.offset + offset
                else:
                    raise ValueError('Seek from end not supported')
            if offset < self.offset:
                raise OSError('Negative seek in write mode')
            count = offset - self.offset
            chunk = b'\0' * 1024
            for i in range(count // 1024):
                self.write(chunk)
            self.write(b'\0' * (count % 1024))
        elif self.mode == READ:
            self._check_not_closed()
            return self._buffer.seek(offset, whence)

        return self.offset 
Example 8
Project: slob   Author: itkach   File: slob.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_seek_and_read(self):

        def mkfile(basename, content):
            part = os.path.join(self.tmpdir.name, basename)
            with fopen(part, 'wb') as f:
                f.write(content)
            return part

        content = b'abc\nd\nefgh\nij'
        part1 = mkfile('1', content[:4])
        part2 = mkfile('2', content[4:5])
        part3 = mkfile('3', content[5:])

        with MultiFileReader(part1, part2, part3) as m:
            self.assertEqual(m.size, len(content))
            m.seek(2)
            self.assertEqual(m.read(2), content[2:4])
            m.seek(1)
            self.assertEqual(m.read(len(content) - 2), content[1:-1])
            m.seek(-1, whence=io.SEEK_END)
            self.assertEqual(m.read(10), content[-1:])

            m.seek(4)
            m.seek(-2, whence=io.SEEK_CUR)
            self.assertEqual(m.read(3), content[2:5]) 
Example 9
Project: onedrive-sdk-python   Author: OneDrive   File: test_file_slice.py    License: MIT License 6 votes vote down vote up
def testSliceFileStartEnd(self):
        with tempfile.TemporaryFile() as f:
            f.write(b'123456789')
            f.flush()
            part = FileSlice(f, 0, 5)
            self.assertEqual(len(part), 5)
            self.assertEqual(part.read(), b'12345')
            self.assertEqual(part.read(3), b'')
            part.seek(0, io.SEEK_SET)
            self.assertEqual(part.read(3), b'123')
            self.assertEqual(part.tell(), 3)
            part.seek(-3, io.SEEK_CUR)
            self.assertEqual(part.tell(), 0)
            part.seek(-2, io.SEEK_END)
            self.assertEqual(part.tell(), 3)
            self.assertEqual(part.readall(), b'45')
            with self.assertRaises(IOError):
                part.write('abc')
            with self.assertRaises(IOError):
                part.writelines(['foo', 'bar']) 
Example 10
Project: onedrive-sdk-python   Author: OneDrive   File: test_file_slice.py    License: MIT License 6 votes vote down vote up
def testSliceFileStartLength(self):
        with tempfile.TemporaryFile() as f:
            f.write(b'123456789')
            f.flush()
            part = FileSlice(f, 0, length=5)
            self.assertEqual(len(part), 5)
            self.assertEqual(part.read(), b'12345')
            self.assertEqual(part.read(3), b'')
            part.seek(0)
            self.assertEqual(part.read(3), b'123')
            self.assertEqual(part.tell(), 3)
            part.seek(-3, io.SEEK_CUR)
            self.assertEqual(part.readall(), b'12345')
            with self.assertRaises(IOError):
                part.write('abc')
            with self.assertRaises(IOError):
                part.writelines(['foo', 'bar']) 
Example 11
Project: onedrive-sdk-python   Author: OneDrive   File: test_file_slice.py    License: MIT License 6 votes vote down vote up
def testSanityChecks(self):
        with tempfile.TemporaryFile() as f:
            f.write(b'123456789')
            f.flush()
            with self.assertRaises(ValueError):
                part = FileSlice(f, -5, -2)
            with self.assertRaises(ValueError):
                part = FileSlice(f, 0, -2)
            with self.assertRaises(ValueError):
                part = FileSlice(f, -10, 2)
            with self.assertRaises(ValueError):
                part = FileSlice(f, 10, 2)
            with self.assertRaises(ValueError):
                part = FileSlice(f, 10, length=-2)

            part = FileSlice(f, 1, 5)
            with self.assertRaises(ValueError):
                part.seek(8)
            with self.assertRaises(ValueError):
                part.seek(8, io.SEEK_SET)
            part.seek(3)
            with self.assertRaises(ValueError):
                part.seek(4, io.SEEK_CUR)
            with self.assertRaises(ValueError):
                part.seek(-5, io.SEEK_END) 
Example 12
Project: onedrive-sdk-python   Author: OneDrive   File: file_slice.py    License: MIT License 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        if whence == io.SEEK_SET:
            desired_pos = self._start + offset
        if whence == io.SEEK_CUR:
            desired_pos = self._handle.tell() + offset
        if whence == io.SEEK_END:
            desired_pos = self._end + offset

        if desired_pos < self._start:
            raise ValueError("Seeking before the file slice")
        if desired_pos > self._end:
            raise ValueError("Seekeing past the end of file slice")

        ret = self._handle.seek(desired_pos, io.SEEK_SET)
        if ret:
            return ret - self._start
        else:
            return ret 
Example 13
Project: ratarmount   Author: mxmlnkn   File: ratarmount.py    License: MIT License 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        if whence == io.SEEK_CUR:
            self.offset += offset
        elif whence == io.SEEK_END:
            self.offset = self.cumsizes[-1] + offset
        elif whence == io.SEEK_SET:
            self.offset = offset

        if self.offset < 0:
            raise Exception("Trying to seek before the start of the file!")
        if self.offset >= self.cumsizes[-1]:
            return self.offset

        i = self._findStencil( self.offset )
        offsetInsideStencil = self.offset - self.cumsizes[i]
        assert offsetInsideStencil >= 0
        assert offsetInsideStencil < self.sizes[i]
        self.fileobj.seek( self.offsets[i] + offsetInsideStencil, io.SEEK_SET )

        return self.offset 
Example 14
Project: PyHDB   Author: SAP   File: message.py    License: Apache License 2.0 6 votes vote down vote up
def pack(self):
        """ Pack message to binary stream. """
        payload = io.BytesIO()
        # Advance num bytes equal to header size - the header is written later
        # after the payload of all segments and parts has been written:
        payload.seek(self.header_size, io.SEEK_CUR)

        # Write out payload of segments and parts:
        self.build_payload(payload)

        packet_length = len(payload.getvalue()) - self.header_size
        self.header = MessageHeader(self.session_id, self.packet_count, packet_length, constants.MAX_SEGMENT_SIZE,
                                    num_segments=len(self.segments), packet_options=0)
        packed_header = self.header_struct.pack(*self.header)

        # Go back to begining of payload for writing message header:
        payload.seek(0)
        payload.write(packed_header)
        payload.seek(0, io.SEEK_END)

        trace(self)

        return payload 
Example 15
Project: PyHDB   Author: SAP   File: segments.py    License: Apache License 2.0 6 votes vote down vote up
def pack(self, payload, **kwargs):

        # remember position in payload object:
        segment_payload_start_pos = payload.tell()

        # Advance num bytes equal to header size. The header is written later
        # after the payload of all segments and parts has been written:
        payload.seek(self.header_size, io.SEEK_CUR)

        # Generate payload of parts:
        self.build_payload(payload)

        segment_length = payload.tell() - segment_payload_start_pos  # calc length of parts payload
        self.header = RequestSegmentHeader(segment_length, self.offset, len(self.parts), self.number, self.segment_kind,
                                           self.message_type, int(kwargs.get('commit', 0)), self.command_options)
        packed_header = self.header_struct.pack(*self.header)

        # Go back to beginning of payload header for writing segment header:
        payload.seek(segment_payload_start_pos)
        payload.write(packed_header)
        # Put file pointer at the end of the bffer so that next segment can be appended:
        payload.seek(0, io.SEEK_END) 
Example 16
Project: VideoSuperResolution   Author: LoSealL   File: VirtualFile.py    License: MIT License 6 votes vote down vote up
def seek(self, offset, where=SEEK_SET):
    """Seek the position by `offset` relative to `where`.

    Args:
        offset: move the read pointer by `offset` bytes.
        where: same as io.SEEK_END, io.SEEK_CUR or io.SEEK_SET.
    """
    if where == SEEK_CUR:
      cur = len(self.read_file)
      pos = cur + offset
    elif where == SEEK_END:
      pos = len(self.read_file) + len(self.file) + offset
    else:
      pos = offset
    if pos < 0:
      pos = 0
    self.file = self.read_file + self.file
    self.read_file = self.file[:pos]
    self.file = self.file[pos:]
    self.cur_fd = None 
Example 17
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: gzip.py    License: GNU General Public License v3.0 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        if self.mode == WRITE:
            if whence != io.SEEK_SET:
                if whence == io.SEEK_CUR:
                    offset = self.offset + offset
                else:
                    raise ValueError('Seek from end not supported')
            if offset < self.offset:
                raise OSError('Negative seek in write mode')
            count = offset - self.offset
            chunk = bytes(1024)
            for i in range(count // 1024):
                self.write(chunk)
            self.write(bytes(count % 1024))
        elif self.mode == READ:
            self._check_not_closed()
            return self._buffer.seek(offset, whence)

        return self.offset 
Example 18
Project: FODI   Author: vcheckzen   File: IcnsImagePlugin.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, fobj):
        """
        fobj is a file-like object as an icns resource
        """
        # signature : (start, length)
        self.dct = dct = {}
        self.fobj = fobj
        sig, filesize = nextheader(fobj)
        if sig != b"icns":
            raise SyntaxError("not an icns file")
        i = HEADERSIZE
        while i < filesize:
            sig, blocksize = nextheader(fobj)
            if blocksize <= 0:
                raise SyntaxError("invalid block header")
            i += HEADERSIZE
            blocksize -= HEADERSIZE
            dct[sig] = (i, blocksize)
            fobj.seek(blocksize, io.SEEK_CUR)
            i += blocksize 
Example 19
Project: echopype   Author: OSOceanAcoustics   File: ek_raw_io.py    License: Apache License 2.0 6 votes vote down vote up
def peek(self):
        '''
        Returns the header of the next datagram in the file.  The file position is
        reset back to the original location afterwards.

        :returns: [dgram_size, dgram_type, (low_date, high_date)]
        '''

        dgram_header = self._read_dgram_header()
        if dgram_header['type'].startswith('RAW0'):
            dgram_header['channel'] = struct.unpack('h', self._read_bytes(2))[0]
            self._seek_bytes(-18, SEEK_CUR)
        elif dgram_header['type'].startswith('RAW3'):
            chan_id = struct.unpack('128s', self._read_bytes(128))
            dgram_header['channel_id'] = chan_id.strip('\x00')
            self._seek_bytes(-(16 + 128), SEEK_CUR)
        else:
            self._seek_bytes(-16, SEEK_CUR)

        return dgram_header 
Example 20
Project: mrcfile   Author: ccpem   File: test_mrcinterpreter.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_permissive_read_mode_with_file_too_small_for_extended_header(self):
        stream = io.BytesIO()
        mrc = MrcInterpreter()
        mrc._iostream = stream
        mrc._create_default_attributes()
        mrc.set_extended_header(np.arange(12, dtype=np.int16).reshape(1, 3, 4))
        mrc.close()
        stream.seek(-1, io.SEEK_CUR)
        stream.truncate()
        stream.seek(0)
        
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            
            MrcInterpreter(iostream=stream, permissive=True)
            
            assert len(w) == 1
            assert ("Expected 24 bytes in extended header but could only read 23"
                    in str(w[0].message)) 
Example 21
Project: mrcfile   Author: ccpem   File: test_mrcinterpreter.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_permissive_read_mode_with_file_too_small_for_data(self):
        stream = io.BytesIO()
        mrc = MrcInterpreter()
        mrc._iostream = stream
        mrc._create_default_attributes()
        mrc.set_data(np.arange(12, dtype=np.int16).reshape(1, 3, 4))
        mrc.close()
        stream.seek(-1, io.SEEK_CUR)
        stream.truncate()
        stream.seek(0)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            MrcInterpreter(iostream=stream, permissive=True)

            assert len(w) == 1
            assert ("Expected 24 bytes in data block but could only read 23"
                    in str(w[0].message)) 
Example 22
Project: exxo   Author: mbachry   File: _exxo_elf.py    License: ISC License 6 votes vote down vote up
def read_header(elf, buffer):
    buffer.seek(0)
    elf_header = elf['elf_header']
    elf_header['file_ident'] = buffer.read(ELF32)
    if elf_header['file_ident'] != ELFSIG:
        raise ValueError('This is not a ELF object')
    file_class = ord(buffer.read(ELF8))
    if file_class == ELFCLASS32:
        hdr_format = elf32_hdr_format
    elif file_class == ELFCLASS64:
        hdr_format = elf64_hdr_format
    else:
        raise ValueError('Unknown ELFCLASS: %d', file_class)
    elf_header['file_class'] = file_class
    elf_header['file_encoding'] = ord(buffer.read(ELF8))
    elf_header['file_version'] = ord(buffer.read(ELF8))
    # ignore 9 bytes
    buffer.seek(9, io.SEEK_CUR)
    load_struct(buffer, elf_header, hdr_format) 
Example 23
Project: android_universal   Author: bkerler   File: gzip.py    License: MIT License 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        if self.mode == WRITE:
            if whence != io.SEEK_SET:
                if whence == io.SEEK_CUR:
                    offset = self.offset + offset
                else:
                    raise ValueError('Seek from end not supported')
            if offset < self.offset:
                raise OSError('Negative seek in write mode')
            count = offset - self.offset
            chunk = b'\0' * 1024
            for i in range(count // 1024):
                self.write(chunk)
            self.write(b'\0' * (count % 1024))
        elif self.mode == READ:
            self._check_not_closed()
            return self._buffer.seek(offset, whence)

        return self.offset 
Example 24
Project: jawfish   Author: war-and-code   File: tarfile.py    License: MIT License 5 votes vote down vote up
def seek(self, position, whence=io.SEEK_SET):
        """Seek to a position in the file.
        """
        if whence == io.SEEK_SET:
            self.position = min(max(position, 0), self.size)
        elif whence == io.SEEK_CUR:
            if position < 0:
                self.position = max(self.position + position, 0)
            else:
                self.position = min(self.position + position, self.size)
        elif whence == io.SEEK_END:
            self.position = max(min(self.size + position, self.size), 0)
        else:
            raise ValueError("Invalid argument")
        return self.position 
Example 25
Project: kobo-predict   Author: awemulya   File: tarfile.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def seek(self, position, whence=io.SEEK_SET):
        """Seek to a position in the file.
        """
        if whence == io.SEEK_SET:
            self.position = min(max(position, 0), self.size)
        elif whence == io.SEEK_CUR:
            if position < 0:
                self.position = max(self.position + position, 0)
            else:
                self.position = min(self.position + position, self.size)
        elif whence == io.SEEK_END:
            self.position = max(min(self.size + position, self.size), 0)
        else:
            raise ValueError("Invalid argument")
        return self.position 
Example 26
Project: buttersink   Author: AmesCornish   File: Butter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def seek(self, offset, whence):
        self.stream.seek(offset, offset, whence)
        if whence == io.SEEK_SET:
            self.bytesRead = offset
        elif whence == io.SEEK_CUR:
            pass
        elif whence == io.SEEK_END:
            self.bytesRead = None 
Example 27
Project: buttersink   Author: AmesCornish   File: Store.py    License: GNU General Public License v3.0 5 votes vote down vote up
def transfer(sendContext, receiveContext, chunkSize):
    """ Transfer (large) data from sender to receiver. """
    try:
        chunkSize = receiveContext.chunkSize
    except AttributeError:
        pass

    if sendContext is not None and receiveContext is not None:
        with receiveContext as writer:
            # Open reader after writer,
            # so any raised errors will abort write before writer closes.
            with sendContext as reader:
                checkBefore = None
                if hasattr(writer, 'skipChunk'):
                    checkBefore = hasattr(reader, 'checkSum')

                while True:
                    if checkBefore is True:
                        (size, checkSum) = reader.checkSum(chunkSize)

                        if writer.skipChunk(size, checkSum):
                            reader.seek(size, io.SEEK_CUR)
                            continue

                    data = reader.read(chunkSize)
                    if len(data) == 0:
                        break

                    if checkBefore is False:
                        checkSum = hashlib.md5(data).hexdigest()

                        if writer.skipChunk(len(data), checkSum, data):
                            continue

                    writer.write(data) 
Example 28
Project: dimod   Author: dwavesystems   File: fileview.py    License: Apache License 2.0 5 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        """Change the stream position to the given `offset`.

        Args:
            offset (int):
                The offset relative to `whence`.

            whence (int):
                In addition to values for whence provided in the :mod:`io`
                module, additional values for whence are:

                    * SEEK_OFFSET or 100 - the start of the offset data
                    * SEEK_LINEAR or 101 - the start of the linear data
                    * SEEK_QUADRATIC or 102 - the start of the quadratic data

        Returns:
            The new stream position.

        """
        if whence == io.SEEK_SET:
            self.pos = offset
        elif whence == io.SEEK_CUR:
            self.pos += offset
        elif whence == io.SEEK_END:
            self.pos = self.quadratic_end + offset
        elif whence == SEEK_OFFSET:
            self.pos = self.offset_start + offset
        elif whence == SEEK_LINEAR:
            self.pos = self.linear_start + offset
        elif whence == SEEK_QUADRATIC:
            self.pos = self.quadratic_start + offset
        else:
            raise ValueError("unknown value for 'whence'")
        return self.pos 
Example 29
Project: teleport   Author: tp4a   File: PcfFontFile.py    License: Apache License 2.0 5 votes vote down vote up
def _load_properties(self):

        #
        # font properties

        properties = {}

        fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)

        nprops = i32(fp.read(4))

        # read property description
        p = []
        for i in range(nprops):
            p.append((i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))))
        if nprops & 3:
            fp.seek(4 - (nprops & 3), io.SEEK_CUR)  # pad

        data = fp.read(i32(fp.read(4)))

        for k, s, v in p:
            k = sz(data, k)
            if s:
                v = sz(data, v)
            properties[k] = v

        return properties 
Example 30
Project: teleport   Author: tp4a   File: TarIO.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, tarfile, file):
        """
        Create file object.

        :param tarfile: Name of TAR file.
        :param file: Name of member file.
        """
        self.fh = open(tarfile, "rb")

        while True:

            s = self.fh.read(512)
            if len(s) != 512:
                raise OSError("unexpected end of tar file")

            name = s[:100].decode("utf-8")
            i = name.find("\0")
            if i == 0:
                raise OSError("cannot find subfile")
            if i > 0:
                name = name[:i]

            size = int(s[124:135], 8)

            if file == name:
                break

            self.fh.seek((size + 511) & (~511), io.SEEK_CUR)

        # Open region
        super().__init__(self.fh, self.fh.tell(), size)

    # Context manager support