![]() |
VOOZH | about |
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 reachedOther methods which we can use are:
Table of Content
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
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 emptyExplanation:
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.