Home > Net >  How to detect EOF when reading a file with readline() in Python?
How to detect EOF when reading a file with readline() in Python?

Time:10-01

I need to read the file line by line with readline() and cannot easily change that. Roughly it is:

with open(file_name, 'r') as i_file:
    while True:
        line = i_file.readline()
        # I need to check that EOF has not been reached, so that readline() really returned something

The real logic is more involved, so I can't read the file at once with readlines() or write something like for line in i_file:.

Is there a way to check readline() for EOF? Does it throw an exception maybe?

It was very hard to find the answer on the internet because the documentation search redirects to something non-relevant (a tutorial rather than the reference, or GNU readline), and the noise on the internet is mostly about readlines() function.

The solution should work in Python 3.6 .

CodePudding user response:

Using this I suggest:

fp = open("input")
while True:
     nstr = fp.readline()
     if len(nstr) == 0:
         break # or raise an exception if you want
     # do stuff using nstr

As Barmar mentioned in the comments, readline "returns an empty string at EOF".

CodePudding user response:

From the documentation:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

with open(file_name, 'r') as i_file:
    while True:
        line = i_file.readline()
        if not line:
            break
        # do something with line

CodePudding user response:

Empty strings returned in case of EOF evaluate to False, so this could be a nice use case for the walrus operator:

with open(file_name, 'r') as i_file:
    while line := i_file.readline():
        # do something with line
  • Related