Python io.SEEK_SET Examples

The following are 30 code examples for showing how to use io.SEEK_SET(). 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: Pyro5   Author: irmen   File: server.py    License: MIT License 6 votes vote down vote up
def annotation_stream(self, with_checksum=False):
        # create a large temporary file
        f = tempfile.TemporaryFile()
        for _ in range(5000):
            f.write(b"1234567890!" * 1000)
        filesize = f.tell()
        f.seek(os.SEEK_SET, 0)
        # return the file data via annotation stream (remote iterator)
        annotation_size = 500000
        print("transmitting file via annotations stream (%d bytes in chunks of %d)..." % (filesize, annotation_size))
        with f:
            while True:
                chunk = f.read(annotation_size)
                if not chunk:
                    break
                # store the file data chunk in the FDAT response annotation,
                # and return the current file position and checksum (if asked).
                current_context.response_annotations = {"FDAT": chunk}
                yield f.tell(), zlib.crc32(chunk) if with_checksum else 0 
Example 3
Project: pyclibrary   Author: MatthieuDartiailh   File: utils.py    License: MIT License 6 votes vote down vote up
def get_shared_library_arch(filename):
    with io.open(filename, 'rb') as fp:
        dos_headers = fp.read(64)
        fp.read(4)

        magic, skip, offset = _struct_unpack(str('2s58sl'), dos_headers)

        if magic != b'MZ':
            raise Exception('Not an executable')

        fp.seek(offset, io.SEEK_SET)
        pe_header = fp.read(6)

        sig, skip, machine = _struct_unpack(str('2s2sH'), pe_header)

        if sig != b'PE':
            raise Exception('Not a PE executable')

        return machine_types.get(machine, 'UNKNOWN') 
Example 4
Project: pycozmo   Author: zayfod   File: test_anim_encoder.py    License: MIT License 6 votes vote down vote up
def test_no_clips(self):
        data = json.loads("""
{
  "clips": []
}       
        """)
        # Load from JSON
        clips = AnimClips.from_dict(data)
        self.assertEqual(len(clips.clips), 0)

        # Save to FB
        f = io.BytesIO()
        clips.to_fb_stream(f)
        f.seek(0, io.SEEK_SET)

        # Load from FB
        clips = clips.from_fb_stream(f)
        self.assertEqual(len(clips.clips), 0)

        # Save to JSON
        data2 = clips.to_dict()
        self.assertEqual(data, data2) 
Example 5
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 6
Project: teleport   Author: tp4a   File: ContainerIO.py    License: Apache License 2.0 6 votes vote down vote up
def seek(self, offset, mode=io.SEEK_SET):
        """
        Move file pointer.

        :param offset: Offset in bytes.
        :param mode: Starting position. Use 0 for beginning of region, 1
           for current offset, and 2 for end of region.  You cannot move
           the pointer outside the defined region.
        """
        if mode == 1:
            self.pos = self.pos + offset
        elif mode == 2:
            self.pos = self.length + offset
        else:
            self.pos = offset
        # clamp
        self.pos = max(0, min(self.pos, self.length))
        self.fh.seek(self.offset + self.pos) 
Example 7
Project: teleport   Author: tp4a   File: TiffImagePlugin.py    License: Apache License 2.0 6 votes vote down vote up
def setup(self):
        # Reset everything.
        self.f.seek(self.beginning, os.SEEK_SET)

        self.whereToWriteNewIFDOffset = None
        self.offsetOfNewPage = 0

        self.IIMM = IIMM = self.f.read(4)
        if not IIMM:
            # empty file - first page
            self.isFirst = True
            return

        self.isFirst = False
        if IIMM == b"II\x2a\x00":
            self.setEndian("<")
        elif IIMM == b"MM\x00\x2a":
            self.setEndian(">")
        else:
            raise RuntimeError("Invalid TIFF file header")

        self.skipIFDs()
        self.goToEnd() 
Example 8
Project: teleport   Author: tp4a   File: ContainerIO.py    License: Apache License 2.0 6 votes vote down vote up
def seek(self, offset, mode=io.SEEK_SET):
        """
        Move file pointer.

        :param offset: Offset in bytes.
        :param mode: Starting position. Use 0 for beginning of region, 1
           for current offset, and 2 for end of region.  You cannot move
           the pointer outside the defined region.
        """
        if mode == 1:
            self.pos = self.pos + offset
        elif mode == 2:
            self.pos = self.length + offset
        else:
            self.pos = offset
        # clamp
        self.pos = max(0, min(self.pos, self.length))
        self.fh.seek(self.offset + self.pos) 
Example 9
Project: teleport   Author: tp4a   File: TiffImagePlugin.py    License: Apache License 2.0 6 votes vote down vote up
def setup(self):
        # Reset everything.
        self.f.seek(self.beginning, os.SEEK_SET)

        self.whereToWriteNewIFDOffset = None
        self.offsetOfNewPage = 0

        self.IIMM = IIMM = self.f.read(4)
        if not IIMM:
            # empty file - first page
            self.isFirst = True
            return

        self.isFirst = False
        if IIMM == b"II\x2a\x00":
            self.setEndian("<")
        elif IIMM == b"MM\x00\x2a":
            self.setEndian(">")
        else:
            raise RuntimeError("Invalid TIFF file header")

        self.skipIFDs()
        self.goToEnd() 
Example 10
Project: python3_ios   Author: holzschu   File: ContainerIO.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def seek(self, offset, mode=io.SEEK_SET):
        """
        Move file pointer.

        :param offset: Offset in bytes.
        :param mode: Starting position. Use 0 for beginning of region, 1
           for current offset, and 2 for end of region.  You cannot move
           the pointer outside the defined region.
        """
        if mode == 1:
            self.pos = self.pos + offset
        elif mode == 2:
            self.pos = self.length + offset
        else:
            self.pos = offset
        # clamp
        self.pos = max(0, min(self.pos, self.length))
        self.fh.seek(self.offset + self.pos) 
Example 11
Project: python3_ios   Author: holzschu   File: TiffImagePlugin.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setup(self):
        # Reset everything.
        self.f.seek(self.beginning, os.SEEK_SET)

        self.whereToWriteNewIFDOffset = None
        self.offsetOfNewPage = 0

        self.IIMM = IIMM = self.f.read(4)
        if not IIMM:
            # empty file - first page
            self.isFirst = True
            return

        self.isFirst = False
        if IIMM == b"II\x2a\x00":
            self.setEndian("<")
        elif IIMM == b"MM\x00\x2a":
            self.setEndian(">")
        else:
            raise RuntimeError("Invalid TIFF file header")

        self.skipIFDs()
        self.goToEnd() 
Example 12
Project: Fluid-Designer   Author: Microvellum   File: bz2.py    License: GNU General Public License v3.0 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        """Change the file position.

        The new position is specified by offset, relative to the
        position indicated by whence. Values for whence are:

            0: start of stream (default); offset must not be negative
            1: current stream position
            2: end of stream; offset must not be positive

        Returns the new file position.

        Note that seeking is emulated, so depending on the parameters,
        this operation may be extremely slow.
        """
        with self._lock:
            self._check_can_seek()
            return self._buffer.seek(offset, whence) 
Example 13
Project: Fluid-Designer   Author: Microvellum   File: lzma.py    License: GNU General Public License v3.0 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        """Change the file position.

        The new position is specified by offset, relative to the
        position indicated by whence. Possible values for whence are:

            0: start of stream (default): offset must not be negative
            1: current stream position
            2: end of stream; offset must not be positive

        Returns the new file position.

        Note that seeking is emulated, so depending on the parameters,
        this operation may be extremely slow.
        """
        self._check_can_seek()
        return self._buffer.seek(offset, whence) 
Example 14
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 15
Project: Imogen   Author: CedricGuillemet   File: bz2.py    License: MIT License 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        """Change the file position.

        The new position is specified by offset, relative to the
        position indicated by whence. Values for whence are:

            0: start of stream (default); offset must not be negative
            1: current stream position
            2: end of stream; offset must not be positive

        Returns the new file position.

        Note that seeking is emulated, so depending on the parameters,
        this operation may be extremely slow.
        """
        with self._lock:
            self._check_can_seek()
            return self._buffer.seek(offset, whence) 
Example 16
Project: Imogen   Author: CedricGuillemet   File: lzma.py    License: MIT License 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        """Change the file position.

        The new position is specified by offset, relative to the
        position indicated by whence. Possible values for whence are:

            0: start of stream (default): offset must not be negative
            1: current stream position
            2: end of stream; offset must not be positive

        Returns the new file position.

        Note that seeking is emulated, so depending on the parameters,
        this operation may be extremely slow.
        """
        self._check_can_seek()
        return self._buffer.seek(offset, whence) 
Example 17
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 18
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 19
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 20
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 21
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 22
Project: PyHDB   Author: SAP   File: lobs.py    License: Apache License 2.0 6 votes vote down vote up
def seek(self, offset, whence=SEEK_SET):
        """Seek pointer in lob data buffer to requested position.
        Might trigger further loading of data from the database if the pointer is beyond currently read data.
        """
        # A nice trick is to (ab)use BytesIO.seek() to go to the desired position for easier calculation.
        # This will not add any data to the buffer however - very convenient!
        self.data.seek(offset, whence)
        new_pos = self.data.tell()
        missing_bytes_to_read = new_pos - self._current_lob_length
        if missing_bytes_to_read > 0:
            # Trying to seek beyond currently available LOB data, so need to load some more first.

            # We are smart here: (at least trying...):
            #         If a user sets a certain file position s/he probably wants to read data from
            #         there. So already read some extra data to avoid yet another immediate
            #         reading step. Try with EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK additional items (bytes/chars).

            # jump to the end of the current buffer and read the new data:
            self.data.seek(0, SEEK_END)
            self.read(missing_bytes_to_read + self.EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK)
            # reposition file pointer a originally desired position:
            self.data.seek(new_pos)
        return new_pos 
Example 23
Project: PyHDB   Author: SAP   File: lobs.py    License: Apache License 2.0 6 votes vote down vote up
def read(self, n=-1):
        """Read up to n items (bytes/chars) from the lob and return them.
        If n is -1 then all available data is returned.
        Might trigger further loading of data from the database if the number of items requested for
        reading is larger than what is currently buffered.
        """
        pos = self.tell()
        num_items_to_read = n if n != -1 else self.length - pos
        # calculate the position of the file pointer after data was read:
        new_pos = min(pos + num_items_to_read, self.length)

        if new_pos > self._current_lob_length:
            missing_num_items_to_read = new_pos - self._current_lob_length
            self._read_missing_lob_data_from_db(self._current_lob_length, missing_num_items_to_read)
        # reposition file pointer to original position as reading in IO buffer might have changed it
        self.seek(pos, SEEK_SET)
        return self.data.read(n) 
Example 24
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 25
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: bz2.py    License: GNU General Public License v3.0 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        """Change the file position.

        The new position is specified by offset, relative to the
        position indicated by whence. Values for whence are:

            0: start of stream (default); offset must not be negative
            1: current stream position
            2: end of stream; offset must not be positive

        Returns the new file position.

        Note that seeking is emulated, so depending on the parameters,
        this operation may be extremely slow.
        """
        with self._lock:
            self._check_can_seek()
            return self._buffer.seek(offset, whence) 
Example 26
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: lzma.py    License: GNU General Public License v3.0 6 votes vote down vote up
def seek(self, offset, whence=io.SEEK_SET):
        """Change the file position.

        The new position is specified by offset, relative to the
        position indicated by whence. Possible values for whence are:

            0: start of stream (default): offset must not be negative
            1: current stream position
            2: end of stream; offset must not be positive

        Returns the new file position.

        Note that seeking is emulated, so depending on the parameters,
        this operation may be extremely slow.
        """
        self._check_can_seek()
        return self._buffer.seek(offset, whence) 
Example 27
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 28
Project: kdztools   Author: ehem   File: mkdz.py    License: GNU General Public License v3.0 6 votes vote down vote up
def write(self, file, name):
		"""
		Write our block to the file with the specified name
		"""
		input = io.FileIO(self.name, "rb")

		l = input.seek(0, io.SEEK_END)
		input.seek(0, io.SEEK_SET)

		print("[+] Writing {:s} to {:s} ({:d} bytes)".format(self.name, name, l))

		buf = b" "
		while len(buf) > 0:
			buf = input.read(4096)
			file.write(buf)

		input.close() 
Example 29
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 30
Project: Pyro5   Author: irmen   File: server.py    License: MIT License 5 votes vote down vote up
def prepare_file_blob(self, size):
        print("preparing file-based blob of size %d" % size)
        file_id = str(uuid.uuid4())
        f = tempfile.TemporaryFile()
        chunk = b"x" * 100000
        for _ in range(size//100000):
            f.write(chunk)
        f.write(b"x"*(size % 100000))
        f.flush()
        f.seek(0, io.SEEK_SET)
        # os.fsync(f)
        datafiles[file_id] = f
        blobsock_info = self._pyroDaemon.blobsocket.getsockname()  # return the port info for the blob socket as well
        return file_id, blobsock_info