How to use tell() method in Python?

A file in a computer is simply an entity that stores/contain information. Python provides various methods for accessing and handling files, often called file handling operations. You can use them to create, open, read, write, modify files on your file system.
In this tutorial, you will learn about one such file handling method, the tell().

Introduction:

Once you open a file, you intend to perform different operations on it. Whenever you want to read/write data to/from the file, you need a reference pointer that indicates where to start from. This is taken care of by the file pointer, also called as file object or file handle.
In simple words, the file object tells you the current position in the file and is helpful in indicating where the upcoming read/write operations are to start. (you can simply relate it with the cursor to understand)

Sometimes, you yourself might want to know this position. The tell() method gives you the position of the file object at that point of time.

Syntax: fileobject.tell()
This method takes no parameters and returns the position of the file object (an integer value) with which it is invoked.

Some examples to show the use of tell() method in Python

Example 1:Let us consider an existing text file “example1.txt“, as shown below.

https://drive.google.com/file/d/1jaLFBsj4ZhEtL-NirZpQvGR30wc2wy9U/view?usp=sharing

As you must be knowing, when you open an existing file, the file pointer is at the beginning of the file. So, by using the tell();

fobject=open("example1.txt","r")
print(fobject.tell())
0

Now, let us read three letters from the file and then check for the file pointer location.

fobject=open("example1.txt","r") 
print(fobject.tell())
print(fobject.read(3))
print(fobject.tell())
0
Wel
3

Further, let us check what happens if we open the file in append mode.

fobject=open("example1.txt","a") 
print(fobject.tell())
20

As you might know, the append mode allows you to append data from the end of the existing data. Thus, the file pointer is positioned at the end.

Example 2: Let us create a new file “example2.txt” and perform tell() operation as shown below.

The file pointer is at 0, as you can see below.

fo=open("example2","w+")
print(fo.tell())
0

Further, let us add some text and observe the position of the file pointer.

fo.write("hello!")
print(fo.tell())
6

 

Note: Another similar method, called as the seek() can be put to use if you want to change the position of the file object(file pointer).
You can read more about them here, File operations for tell() and seek() functions in Python

A related topic you can check out, How to append data to a file in Python

Leave a Reply

Your email address will not be published.