A file iteration question/problem
Arnaud Delobelle
arnodel at googlemail.com
Mon Apr 7 14:54:28 EDT 2008
On Apr 7, 2:09 pm, tinn... at isbd.co.uk wrote:
> Arnaud Delobelle <arno... at googlemail.com> wrote:
> > 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?
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']]
>>>
--
Arnaud
More information about the Python-list
mailing list