Python End of File

Lakshay Kapoor Oct 10, 2023
  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
Python End of File

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.

Lakshay Kapoor avatar Lakshay Kapoor avatar

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.

LinkedIn

Related Article - Python File