Python io.SEEK_CUR Examples
The following are 30
code examples of io.SEEK_CUR().
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 also want to check out all available functions/classes of the module
io
, or try the search function
.

Example #1
Source File: qtutils.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
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
Source File: cfb.py From pyaaf2 with MIT License | 6 votes |
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
Source File: IcnsImagePlugin.py From teleport with Apache License 2.0 | 6 votes |
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
Source File: IcnsImagePlugin.py From teleport with Apache License 2.0 | 6 votes |
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
Source File: IcnsImagePlugin.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Source File: gzip.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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
Source File: gzip.py From Imogen with MIT License | 6 votes |
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
Source File: slob.py From slob with GNU General Public License v3.0 | 6 votes |
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
Source File: test_file_slice.py From onedrive-sdk-python with MIT License | 6 votes |
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
Source File: test_file_slice.py From onedrive-sdk-python with MIT License | 6 votes |
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
Source File: test_file_slice.py From onedrive-sdk-python with MIT License | 6 votes |
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
Source File: file_slice.py From onedrive-sdk-python with MIT License | 6 votes |
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
Source File: ratarmount.py From ratarmount with MIT License | 6 votes |
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
Source File: message.py From PyHDB with Apache License 2.0 | 6 votes |
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
Source File: segments.py From PyHDB with Apache License 2.0 | 6 votes |
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
Source File: VirtualFile.py From VideoSuperResolution with MIT License | 6 votes |
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
Source File: gzip.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
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
Source File: IcnsImagePlugin.py From FODI with GNU General Public License v3.0 | 6 votes |
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
Source File: ek_raw_io.py From echopype with Apache License 2.0 | 6 votes |
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
Source File: test_mrcinterpreter.py From mrcfile with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Source File: test_mrcinterpreter.py From mrcfile with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Source File: _exxo_elf.py From exxo with ISC License | 6 votes |
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
Source File: gzip.py From android_universal with MIT License | 6 votes |
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
Source File: tarfile.py From jawfish with MIT License | 5 votes |
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
Source File: tarfile.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
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
Source File: Butter.py From buttersink with GNU General Public License v3.0 | 5 votes |
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
Source File: Store.py From buttersink with GNU General Public License v3.0 | 5 votes |
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
Source File: fileview.py From dimod with Apache License 2.0 | 5 votes |
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
Source File: PcfFontFile.py From teleport with Apache License 2.0 | 5 votes |
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
Source File: TarIO.py From teleport with Apache License 2.0 | 5 votes |
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