fob.seek(offset, from_where)
offset : Position of file object is considered by adding offset value. 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)
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()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.