Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read specific bytes of file in python

Tags:

python

seek

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

like image 859
user3124171 Avatar asked Mar 31 '15 19:03

user3124171


People also ask

How do I read a specific part of a file in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.

How do I read an offset file in Python?

Description. Python file method seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end. There is no return value.

What is RB mode in Python?

rb : Opens the file as read-only in binary format and starts reading from the beginning of the file. While binary format can be used for different purposes, it is usually used when dealing with things like images, videos, etc. r+ : Opens a file for reading and writing, placing the pointer at the beginning of the file.


2 Answers

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.
like image 72
Brian Burns Avatar answered Sep 29 '22 18:09

Brian Burns


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'
like image 42
Santa Avatar answered Sep 29 '22 19:09

Santa