Seek() and Tell() Function in Python
When we open a file to perform read / write operation, there is a cursor which move inside the file. Whatever the operation(read / write) we perform, that operation will be done at the cursor position.
Within a file, we can get the current position of cursor and move the cursor. To do this python gives us two functions,
tell() Function in Python
tell() function, returns the current position of the file pointer(cursor) in a stream.
f = open("test.txt", "r") cursor_position = f.tell() print("Cursor Position is :",cursor_position) data = f.read(5) print("After reading 5 data from file") cursor_position = f.tell() print("Cursor Position is :",cursor_position)OUTPUT
Cursor Position is : 0 After reading 5 data from file Cursor Position is : 5
As we can see in the output, when we open the file, cursor is at beginning (0 position), after reading 5 bytes data, cursor position gets change.
Seek() Function in Python
As we have seen in the above example that when we open a file, cursor is at beginning (0 position). Sometimes, it is required
that perform the operation (read / write) from the specific position, and move this cursor around without making any
variable read or write, for this purpose there is a
seek() function available to move the cursor to the desired location within a file.
In the above syntax, offset tells how may number of bytes to move forward and start_from is optional, it tells from which place we want to start.
There are three possible values for start_from --
- 0 :beginning of file
- 1 :current position of file
- 2 :end of file
If the argument start_from is not specified, by default it is 0.
Reference point(start_from) at current position / end of file cannot be set in text mode except when offset is equal to 0.
EXAMPLE : Let's suppose there is file test.txt which contains the following text.
If you want to earn something, first learn something.
f = open("abc.txt", "r") f.seek(15) print("Cursor Position :",f.tell()) data = f.read() print(data)OUTPUT
Cursor Position : 15 earn something, first learn something.
Seek() function with negative value:
Seek() function with negative offset value will work, if file is open in binary mode.
f = open("abc.txt", "rb") f.seek(-10, 2) print("Cursor Position :",f.tell()) data = f.read().decode('utf-8') print(data)OUTPUT
Cursor Position : 43 something.
Next chapter is Anonymous Function
Training For College Campus
We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.
Please mail your requirement at firstname.lastname@example.org
Projects For Students
Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.
Students can mail requirement at email@example.com