Show how seek() and tell() move and report the file pointer
Expt. No.10
Page No.20
seek() and tell()
Aim
To write a Python program that reads parts of a text file and uses tell() to report and seek() to move the file pointer.
Concepts used
Algorithm
- Open the file in read mode and display tell() (0 at the start).
- Read 10 characters and display them and the new position.
- seek(0) back to the start and read 6 characters again.
- seek(7) and read 9 characters from there.
Program
# Moving the file pointer with seek() and tell() with open("story.txt", "r") as f: print("Position at the start :", f.tell()) data = f.read(10) print("First 10 characters :", data) print("Position after reading :", f.tell()) f.seek(0) print("After seek(0), position:", f.tell()) print("Read 6 characters again:", f.read(6)) f.seek(7) print("9 characters from 7 :", f.read(9)) print("Position now :", f.tell())
A marked line continues the line above it. In your file, write it on the same line.
Input file
story.txt1 line
Python was created by Guido van Rossum.
Output
$ python seek_and_tell.py
Position at the start : 0
First 10 characters : Python was
Position after reading : 10
After seek(0), position: 0
Read 6 characters again: Python
9 characters from 7 : was creat
Position now : 16
✓ Printed by running this program, not typed by hand.
Result
The pointer started at 0, moved to 10 after reading "Python was", went back to 0 with seek(0), and after seek(7) the next 9 characters read were "was creat", leaving the pointer at 16.
Viva voce: what the examiner may ask
01What does tell() return?
The current position of the file pointer, counted in bytes from the start of the file.
02What does seek(0) do?
It moves the pointer back to the start of the file, so the file can be read again.
03What does read(10) do?
It reads the next 10 characters from the current position and moves the pointer forward by 10.
Variations for the lab test
- Display the last 10 characters of the file using
seek(). - Read the file twice, once with
read()and once afterseek(0). - Display the position after each
readline()call.
! Common mistake Calling
read() a second time without seek(0) returns an empty string, because the pointer is already at the end.