Python End of File

  1. Use file.read() 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 file.read() to Find End of File in Python

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

Example:

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

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.

Example:

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

file_text.close()

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.

Example:

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

while (f := file.read()):
    process(f)

file.close()

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

  • Move Files From One Directory to Another Using Python
  • Get Number of Lines in a File in Python