The tell()
function returns the position of the ‘read’ or ‘write’ pointer in a file.
No parameters go inside the tell()
function.
This function is used with the file object and is declared as:
The return value is an integer that indicates the current position of the pointer in the file in bits.
Here, the tell()
function is called upon the file object, which opens the text_file.txt
file in read mode. This file is twenty bits long. Firstly, the read()
method reads the first five bits of the file and prints them. Then, it reads it beyond the last bit, i.e, the twentieth bit. Since the file is twenty bits long, the tell()
function cannot read the content beyond it and returns the total number of bits in the file.
# opening the filefile_object = open("text_file.txt", "r")# determining the position of the pointerprint(file_object.tell())# read the first five character in the file and print them using the tell() functionprint(file_object.read(5))print(file_object.tell())# read the remaining characters in the file and print them using the tell() functionprint(file_object.read(21))print(file_object.tell())# closing the filefile_object.close()
The read/write position of binary files can also be determined through the tell()
function. In the example below, binary_file.txt
is an empty file. It is opened in tell()
function shows the position of the pointer, which is zero. This indicates an empty file. Then, eleven bits are written into the file with the write()
function, after which the tell()
function determines the updated position of the pointer in the file.
# opening the binary filefp = open("binary_file.txt", "wb")# determining the position of the pointerprint(fp.tell())# writing to the filefp.write(b'10101010101')# determining the position of the pointerprint(fp.tell())# closing the filefp.close()