seek()

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


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer