File Positions in Python

Table of Contents

File Positions

There are two more methods of file objects used to determine or get files positions.

    tell()
    seek()

tell():

This method is used to tell us the current position within the file which means the next read or write operation will be performed that many bytes away from the start of the file.
Syntax :

obj.tell()

Example :

"""
Author : ITVoyagers (https://itvoyagers.in/)


Date :23rd December 2018

Description : Program to use of tell()
"""

#create file object and show the use tell()
object=open("itvoyagers.txt",'w')
object.write("first statement n")
object.write("second statement n")
object=open("itvoyagers.txt",'r')
s=11
c=object.read(s)
print(object.tell()) #tells the position based on parameter passed in read operation
g=object.read()
print(object.tell()) #tells position after performing read() on entire file

seek():

This method is used to change the current position of file.This method has two main parameters offset and from.
Syntax :

obj.seek(offset,from)

Here, offset argument means the number of bytes to be moved.
from argument is used to specify the reference position from where the bytes needs to be moved.
Points to Remember for “from” argument

    if from is set to 0 ,it means use the beginning of the file as reference position
    if from is set to 1 ,it means use the current position of the file as reference position
    if from is set to 2 ,it means use the end of the file as reference position

Example :

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :23rd December 2018

Description : Program to use of seek()
"""

#create file object and show the use seek()
with open("itvoyagers.txt","r") as f:
s=10
c=f.read(s) #reads till 10 char
print(c,end=' ') #adds space after first read()
f.seek(0,0) #goes to start position in file
c=f.read(s)
print(c)
f.seek(0,1) #goes to current position in file
c=f.read(s)
print(c)
f.seek(0,2) #goes to end position in file
c=f.read(s)
print(c)


You can also check other file related operations and modes

Leave a Comment