VOOZH about

URL: https://www.geeksforgeeks.org/python/check-end-of-file-in-python/

⇱ Check end of file in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check end of file in Python

Last Updated : 23 Jul, 2025

In Python, checking the end of a file is easy and can be done using different methods. One of the simplest ways to check the end of a file is by reading the file's content in chunks. When read() method reaches the end, it returns an empty string.

Output:

End of file reached

Other methods which we can use are:

Using for Loop

Python provides a cleaner way to read through files using a for loop. The for loop automatically stops when it reaches the end of the file.

Output:

hello world
End of file reached

Using file.seek() and file.tell()

In some cases, we may want to check the file position manually using seek() and tell(). The tell() function gives the current position of the file pointer, and seek() moves it to a specific location.

Output:

The file is not empty

Explanation:

This method checks the file size by moving the pointer to the end of the file. Since file.txt contains text, the tell() function will return a position greater than 0, so the message "The file is not empty" is printed.

Comment
Article Tags: