16

I want to specify an offset and then read the bytes of a file like

offset = 5
read(5) 

and then read the next 6-10 etc. I read about seek but I cannot understand how it works and the examples arent descriptive enough.

seek(offset,1) returns what?

Thanks

1
  • 2
    A hint: make sure you open the file for binary access, for example: open(filename, 'rb'). Commented Mar 31, 2015 at 19:11

3 Answers 3

17

The values for the second parameter of seek are 0, 1, or 2:

0 - offset is relative to start of file
1 - offset is relative to current position
2 - offset is relative to end of file

Remember you can check out the help -

>>> help(file.seek)
Help on method_descriptor:

seek(...)
    seek(offset[, whence]) -> None.  Move to new file position.

    Argument offset is a byte count.  Optional argument whence defaults to
    0 (offset from start of file, offset should be >= 0); other values are 1
    (move relative to current position, positive or negative), and 2 (move
    relative to end of file, usually negative, although many platforms allow
    seeking beyond the end of a file).  If the file is opened in text mode,
    only offsets returned by tell() are legal.  Use of other offsets causes
    undefined behavior.
    Note that not all file objects are seekable.
Sign up to request clarification or add additional context in comments.

Comments

16

Just play with Python's REPL to see for yourself:

[...]:/tmp$ cat hello.txt 
hello world
[...]:/tmp$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('hello.txt', 'rb')
>>> f.seek(6, 1)    # move the file pointer forward 6 bytes (i.e. to the 'w')
>>> f.read()        # read the rest of the file from the current file pointer
'world\n'

2 Comments

while True: fo.seek(offset,1) b = fo.read() print b by doing that b prints all the bytes except the first "offset" ones... I am just confused...
OP does not specify from whence the offset is calculated. If it's the beginning of the file, it should be f.seek(6, 0) or just f.seek(6). Here it will make no difference because there were no intermediate reads on the open file to change the current stream position. Since the OP wants the next five characters after an offset of six the read should probably be f.read(5).
3

seek doesn't return anything useful. It simply moves the internal file pointer to the given offset. The next read will start reading from that pointer onwards.

2 Comments

Well, it should return None :P
seek() returns the index it now points too within the file. This is also useful if you point o beyond the length of the file or use relative seek() commands.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.