seek()
Python File
fob.seek(offset, from_where)
offset : Position of file object is considered by adding offset value.
from_where : (optional ) 0 (default) starting , 1 relative to current position, 2 end of the file.
The return value is position in bytes.
In text mode ( r )
fob=open('data.txt','r')
fob.seek(5)
print(fob.read())
fob.close()
Output is here ( used the data.txt file given at file read() )
is first line
This is second line
This is thrird line
This is fourth line
In this mode ( 'rt' ) we can't use from_where value as 1 ,however 2 is allowed only when offset is 0
fob=open('data.txt','rt')
fob.seek(0,2)
print(fob.read())
fob.close()
Below code will generate error as we are not using mode as b
fob.seek(0,1)
Using binary mode ( 'rb' )
Offset from the end of the file ( from_where = 2 )
fob=open('data.txt','rb')
print(fob.readline())
fob.seek(-5,2)
print(fob.read())
fob.close()
Output
b'This is first line\r\n'
b' line'
From the relative position of the object ( after the first line )
fob=open('data.txt','rb')
print(fob.readline())
fob.seek(5,1)
print(fob.read())
fob.close()
Output
b'This is first line\r\n'
b'is second line\r\nThis is thrird line\r\nThis is fourth line'
We can read the file position by tell() »
« File Append
File Write »
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com