A file iteration question/problem

T

tinnews

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?
 
A

Arnaud Delobelle

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?

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
 
T

tinnews

Arnaud Delobelle said:
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)
Does that work though? If you iterate through the file with the "for
line in lines:" in the first call of recfun(lines) you surely can't do
"for line in lines:" and get any sort of sensible result in recursive
calls of recfun(lines) can you?
 
P

Peter Otten

Does that work though? If you iterate through the file with the "for
line in lines:" in the first call of recfun(lines) you surely can't do
"for line in lines:" and get any sort of sensible result in recursive
calls of recfun(lines) can you?

Don't speculate, try it.

Peter
 
G

Gabriel Genellina

Does that work though? If you iterate through the file with the "for
line in lines:" in the first call of recfun(lines) you surely can't do
"for line in lines:" and get any sort of sensible result in recursive
calls of recfun(lines) can you?

Why not? Test and see what happens.
 
A

Arnaud Delobelle

Does that work though?  If you iterate through the file with the "for
line in lines:" in the first call of recfun(lines) you surely can't do
"for line in lines:" and get any sort of sensible result in recursive
calls of recfun(lines) can you?

Try it! The keyword is iterator.

Here is an example of how this would work, but since you didn't
believe me I changed the context (strings not files) and I didn't make
it as simple as possible ;)

def reclist(string):
chariter = iter(string + ' ')
def rec():
l = []
word = ''
for c in chariter:
if c.isalnum():
word += c
elif word and (c.isspace() or c in '[]'):
l.append(word)
word = ''
if c == ']':
return l
elif c == '[':
l.append(rec())
return l
return rec()
reclist('40 and 2 eggs but no spam') ['40', 'and', '2', 'eggs', 'but', 'no', 'spam']
reclist('[[40 and 2] eggs] but [no spam]') [[['40', 'and', '2'], 'eggs'], 'but', ['no', 'spam']]
 
J

John Nagle

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)
Don't do that; Python doesn't have tail recursion and you'll hit the
stack limit.

John Nagle
 
A

Arnaud Delobelle

     Don't do that; Python doesn't have tail recursion and you'll hit the
stack limit.

                                John Nagle

This function is not tail recursive (the recursive call is in a loop).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top