Manipulating File Pointer
in Python
Using seek() method with examples
File Pointer
When a file is opened, Python maintains a file
pointer indicating the current position in the
file.
All read/write operations happen from this
position.
Initially, the pointer is at the start of the
file.
seek()
Used to move the file pointer to a specific
position in the file.
Syntax:
file_object.seek(offset,
whence)
offset → number of bytes to move.
whence → reference point (default 0):
0 → beginning of file
1 → current file position
2 → end of file
seek()
Example 1
f = open("[Link]", "r")
print([Link](5)) # Read first 5 characters
[Link](0) # Move pointer to beginning
print([Link]()) # Read full content again
[Link]()
seek()
Example 2
f = open("[Link]", "r")
[Link](7) # Move pointer 7 chars ahead
[Link](2, 1) # Move pointer 2 more chars
from current position
print([Link](5)) # Read next 5 characters
[Link]()
Program
Open a file [Link] and read the first 10
characters, then move the pointer back to
the beginning and read the first 20
characters.
Open a file and read the last 10 characters
using seek() from the end of the file.
Open a file and read the first 5 characters,
then use tell() to print the current file pointer
position.
Given a large text file, write a program to
read only every 5th character using seek()