How to Find the End of a File in Python

Locating the end of a file in Python is a procedure that may appear to be difficult, but is actually pretty straightforward when you have got clear instructions to follow.

In this tutorial, we shall take a closer look at how you can easily achieve this task by going through clear step-by-step instructions. This is a must-know for someone who works on writing Python scripts to handle files. Let’s get started.

Example File

Here is an example of ‘example_file.txt’:

Content of example_file.txt
This is a simple text file
used for demonstration.
Total three lines

Step 1: Open The File

You begin by opening up the chosen file with Python’s built-in open() function. This function typically requires two argument inputs: the name of the file (a string) and the mode which essentially designates how you plan to interact with the file (also a string).

It’s good to remember that Python provides several modes for file opening, but for moving to the end of the file, we’ll use “r” mode to read from a file, or “a” mode to append to a file.

Step 2: Move The Reader’s Position

Next, you’ll employ the seek() function to actually move the reader position. This function goes back or forward to an exact position in the opened file where you’ve defined it. If you want to seek to end of a file you need to use os standard Python module and its function SEEK_END.

Step 3: Verify The Position

You can confirm the reader position with the tell() function. This function will return you the current position of your cursor. That should give you the total byte length of the file since it is located at the end of the file.

Code

Here is the whole code for moving to the end of a file:

Output

After running the mentioned code with ‘example_file.txt’ as the opened file, the Python script should return:

Position of cursor:  53

It meant that our example file is 53 bytes long.

Conclusion

Conclusively, reaching the end of a file in Python needs the careful application of the functions open(), seek(), tell(), and a standard Python module os.

Python provides a really convenient and clear interface for dealing with files, thanks to these inbuilt functions and modules. This tutorial was aimed at simplifying the understanding and usage of moving to the end of a file in Python.