"Maximum recursion depth exceeded"...why?

Thomas Allen thomasmallen at gmail.com
Wed Feb 18 00:52:56 CET 2009


On Feb 17, 6:05 pm, Peter Otten <__pete... at web.de> wrote:
> Thomas Allen wrote:
> > On Feb 17, 5:31 pm, Peter Otten <__pete... at web.de> wrote:
> >> Thomas Allen wrote:
> >> > I must not be understanding something. This is a simple recursive
> >> > function that prints all HTML files in argv[1] as its scans the
> >> > directory's contents. Why do I get a RuntimeError for recursion depth
> >> > exceeded?
>
> >> > #!/usr/bin/env python
>
> >> > import os, sys
>
> >> > def main():
> >> > absToRel(sys.argv[1], sys.argv[2])
>
> >> > def absToRel(dir, root):
> >> > for filename in os.listdir(dir):
>
> >> filename = os.path.join(dir, filename)
>
> >> > if os.path.isdir(filename):
> >> > absToRel(filename, root)
> >> > else:
> >> > if(filename.endswith("html") or filename.endswith("htm")):
> >> > print filename
>
> >> > if __name__ == "__main__":
> >> > main()
>
> >> Without the addition for a directory and a subdirectory of the same
> >> name, "dir/dir", os.listdir("dir") has "dir" (the child) in the result
> >> list which triggers an absToRel() call on "dir" (the parent) ad
> >> infinitum.
>
> >> Peter
>
> > I have two problems in this case:
>
> > 1. I don't know how to reliably map the current filename to an
> > absolute path beyond the top-most directory because my method of doing
> > so would be to os.path.join(os.getcwd(), filename)
>
> Don't make things more complicated than necessary. If you can do
> os.listdir(somedir) you can also do [os.path.join(somedir, fn) for fn in
> os.listdir(somedir)].
>
> > 2. For some reason, only one folder in the directory gets marked as a
> > directory itself when there are about nine others in the top-most
> > directory. I don't even know where to begin to solve this one.
>
> > I'm sure the first is an easy answer, but what do I need to do to
> > solve the second?
>
> If you solve the first properly the second might magically disappear. This
> is what my crystal ball tells me because there is no code in sight...
>
> Peter

I'm referring to the same code, but with a print:

for file in os.listdir(dir):
    if os.path.isdir(file):
        print "D", file

in place of the internal call to absToRel...and only one line prints
such a message. I mean, if I can't trust my OS or its Python
implementation (on a Windows box) to recognize a directory, I'm
wasting everyone's time here.

In any case, is this the best way to go about the problem in general?
Or is there already a way to recursively walk a directory, aware of
the current depth?

Thanks,
Thomas



More information about the Python-list mailing list