A file iteration question/problem

Arnaud Delobelle arnodel at googlemail.com
Sun Apr 6 18:18:09 CEST 2008


On Apr 6, 4:40 pm, tinn... at isbd.co.uk wrote:
> I want to iterate through the lines of a file in a recursive function
> so I can't use:-
>
>     f = open(listfile, 'r')
>     for ln in f:
>
> because when the function calls itself it won't see any more lines in
> the file.  E.g. more fully I want to do somthing like:-
>
> def recfun(f)
>     while True:
>         str = readline(f)
>         if (str == "")
>             break;
>         #
>         # do various tests
>         #
>         if <something>:
>             recfun(f)
>
> Is there no more elegant way of doing this than that rather clumsy
> "while True" followed by a test?
>
> --
> Chris Green

You could use an iterator over the lines of the file:

def recfun(lines):
    for line in lines:
        # Do stuff
        if condition:
            recfun(lines)

lines = iter(open(filename))
recfun(lines)

Or if you want the filename to be the argument of you function, wrap
it in a non-recursive function:

def fun(filename):
    lines = iter(open(filename))
    def recfun():
        for line in lines:
            # Do stuff
            if condition:
                recfun()
    recfun()

HTH

--
Arnaud




More information about the Python-list mailing list