Python End of File

  1. Use to Find End of File in Python
  2. Use the readline() Method With a while Loop to Find End of File in Python
  3. Use Walrus Operator to Find End of File in Python

EOF stands for End Of File. This is the point in the program where the user cannot read the data anymore. It means that the program reads the whole file till the end. Also, when the EOF or end of the file is reached, empty strings are returned as the output. So, a user needs to know whether a file is at its EOF.

This tutorial introduces different ways to find out whether a file is at its EOF in Python.

Use to Find End of File in Python

The method is a built-in Python function used to read the contents of a given file. If the method returns an empty string as an output, which means that the file has reached its EOF.


with open("randomfile.txt", "r") as f:
    while True:
        file_eof =
        if file_eof == '':
            print('End Of File')

Note that when we call the open() function to open the file at the starting of the program, we use "r" as the mode to read the file only. Finally, we use the if conditional statement to check the returned output at the end is an empty string.

Use the readline() Method With a while Loop to Find End of File in Python

The file.readline() method is another built-in Python function to read one complete text file line.

The while loop in Python is a loop that iterates the given condition in a code block till the time the given condition is true. This loop is used when the number of iterations is not known beforehand.

Using the while loop with the readline() method helps read lines in the given text file repeatedly.


file_path = 'randomfile.txt'

file_text = open(file_path, "r")

a = True

while a:
    file_line = file_text.readline()
    if not file_line:
        print("End Of File")
        a = False


The while loop will stop iterating when there will be no text left in the text file for the readline() method to read.

Use Walrus Operator to Find End of File in Python

The Walrus operator is a new operator in Python 3.8. It is denoted by := . This operator is basically an assignment operator which is used to assign True values and then immediately print them.


file = open("randomfile.txt", "r")

while (f :=


Here, the True values are the characters that the read() function will read from the text file. That means it will stop printing once the file is finished.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python File

  • Get All the Files of a Directory
  • Delete a File and Directory in Python
  • Append Text to a File in Python
  • Check if a File Exists in Python