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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
Source File: undz.py From kdztools with GNU General Public License v3.0 | 5 votes |
def extractChunk(self, file, name): """ Extract the payload of our chunk into the file with the name Extracts our payload from the compressed DZ file using ZLIB. self function could be particularly memory-intensive when used with large chunks, as the entire compressed chunk is loaded into RAM and decompressed. A better way to do self would be to chunk the zlib compressed data and decompress it with zlib.decompressor() and a while loop. I'm lazy though, and y'all have fast computers, so self is good enough. """ if name: print("[+] Extracting {:s} to {:s}".format(self.chunkName.decode("utf8"), name)) # Create a hole at the end of the wipe area if file: current = file.seek(0, io.SEEK_CUR) # # Ensure space is allocated to areas to be written # for addr in range(self.trimCount): # file.seek(1<<self.dz.shiftLBA, io.SEEK_CUR) # file.write(b'\x00') # file.seek(current, io.SEEK_SET) # Makes the output the correct size, by filling as hole file.truncate(current + (self.trimCount<<self.dz.shiftLBA)) # Write it to file file.write(self.extract()) # Print our messages self.Messages()
Example #25
Source File: ek_raw_io.py From echopype with Apache License 2.0 | 5 votes |
def seek(self, offset, whence): ''' Performs the familiar 'seek' operation using datagram offsets instead of raw bytes. ''' if whence == SEEK_SET: if offset < 0: raise ValueError('Cannot seek backwards from beginning of file') else: self._seek_bytes(0, SEEK_SET) self._current_dgram_offset = 0 elif whence == SEEK_END: if offset > 0: raise ValueError('Use negative offsets when seeking backward from end of file') #Do we need to generate the total number of datagrams w/in the file? try: self._set_total_dgram_count() #Throws a value error if _total_dgram_count has alread been set. We can ignore it except ValueError: pass self._seek_bytes(0, SEEK_END) self._current_dgram_offset = self._total_dgram_count elif whence == SEEK_CUR: pass else: raise ValueError('Illegal value for \'whence\' (%s), use 0 (beginning), 1 (current), or 2 (end)' % (str(whence))) if offset > 0: for k in range(offset): self.skip() elif offset < 0: for k in range(-offset): self.skip_back()
Example #26
Source File: writer.py From ppci with BSD 2-Clause "Simplified" License | 5 votes |
def export_object(self, obj, e_type): """ Main invocation point to generate an ELF file. """ logger.debug("Saving %s bits ELF file", self.header_types.bits) self.obj = obj self.e_type = e_type self.write_identification() self.elf_header = self.elf_file.header_types.ElfHeader() self.program_headers = [] self.section_headers = [] self.string_table = StringTable() self.section_numbers = {} self.symbol_id_map = {} # Skip over elf header, will come back to this. self.f.seek(self.header_types.ElfHeader.size, io.SEEK_CUR) self.page_size = 0x1000 if self.obj.images and self.e_type == ET_EXEC: self.write_images() self.write_sections() self.write_symbol_table() if self.e_type == ET_REL: self.write_rela_table() self.write_string_table() self.write_section_headers() self.f.seek(self.e_ident_size) self.write_elf_header() self.write_program_headers()
Example #27
Source File: test_mmap.py From compoundfiles with MIT License | 5 votes |
def test_seek_n_tell(test_map): test_map.seek(0) assert test_map.tell() == 0 test_map.seek(0, io.SEEK_END) assert test_map.tell() == 26 test_map.seek(-3, io.SEEK_CUR) assert test_map.tell() == 23 test_map.seek(0, io.SEEK_SET) assert test_map.tell() == 0
Example #28
Source File: test_upload.py From dwave-cloud-client with Apache License 2.0 | 5 votes |
def test_file_interface(self): data = self.data size = len(data) fp = io.BytesIO(data) gf = GettableFile(fp) fv = FileView(gf) # partial read self.assertEqual(fv.read(1), data[0:1]) # read all, also check continuity self.assertEqual(fv.read(), data[1:]) # seek and tell self.assertEqual(len(fv), size) self.assertEqual(fv.seek(2), 2) self.assertEqual(fv.tell(), 2) self.assertEqual(fv.seek(2, io.SEEK_CUR), 4) self.assertEqual(fv.tell(), 4) self.assertEqual(fv.seek(0, io.SEEK_END), size) self.assertEqual(fv.tell(), size) # IOBase derived methods fv.seek(0) self.assertEqual(fv.readlines(), [data])
Example #29
Source File: tarfile.py From android_universal 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 #30
Source File: test_function.py From compoundfiles with MIT License | 5 votes |
def test_stream_seek(): with cf.CompoundFileReader('tests/example.dat') as doc: with doc.open('Storage 1/Stream 1') as f: assert f.seek(0, io.SEEK_END) == 544 assert f.seek(0, io.SEEK_CUR) == 544 with pytest.raises(ValueError): f.seek(-1)