Python 3 – File tell() Method
The tell() method in Python is used to get the current position of the file pointer within a file. The file pointer is the position within the file where the next read or write operation will start. The tell() method returns an integer value that represents the byte offset from the beginning of the file.
Syntax
file.tell()
Parameters
This method does not take any parameters.
Return Value
This method returns an integer that represents the byte offset from the beginning of the file.
Example
Here’s an example of how to use the tell() method in Python:
# Open file in read mode
file = open("example.txt", "r")
# Read the first line from the file
line = file.readline()
print("Line 1: " + line)
# Get the current position of the file pointer
position = file.tell()
print("Position: " + str(position))
# Read the second line from the file
line = file.readline()
print("Line 2: " + line)
# Get the current position of the file pointer again
position = file.tell()
print("Position: " + str(position))
# Close the file
file.close()
Output:
Line 1: This is the first line of text in the file.
Position: 43
Line 2: This is the second line of text in the file.
Position: 88
In this example, we first open a file named example.txt
in read mode. We then read the first line from the file using the readline()
method and print it to the console.
Next, we use the tell() method to get the current position of the file pointer, which is the byte offset from the beginning of the file. We print this position to the console.
Then, we read the second line from the file using the readline()
method and print it to the console. We then use the tell() method again to get the current position of the file pointer and print it to the console.
Finally, we close the file using the close()
method.
Conclusion
In conclusion, the tell() method in Python is useful for getting the current position of the file pointer within a file. This method returns an integer value that represents the byte offset from the beginning of the file. By using this method, you can determine where you are in a file and perform operations accordingly.