-3

I would like to implement a recursive function that takes a file as input and processes the lines. The recursion stops when a condition is met or when I am at the end of file.

The problem is I can not find a way to check if I am at the end of the file.

For instance the following code looking for a line meeting condition won't stop if you reach the end of file.

def f_rec(file):
    line=file.readline()
    if not condition(line): # or file end
        return f_rec(file)
    else:
        return line

I am happy with using another data structure than a file object, but it has to be lazily reading the file. I do not want to use a for loop, because I like functional programming. There may be empty lines in my file.

Edit:

To clarify:

This is not a duplicate of any question asking how to check if you are at the end of file. I know very well that you can do this:

for line in file:
   if condition(line):
      return line

What I want to know really is whether or not it there is a way to apply a recursive function to a file, with the file still being read lazily.

bkhantun
  • 71
  • 4

1 Answers1

1

.readline() will return an empty string when it reaches the end of the file, and empty strings are false so this would work

def f_rec(file):
    line=file.readline()
    if line:
        return f_rec(file)
    else:
        return line
geckos
  • 5,687
  • 1
  • 41
  • 53