Problem opening files while using os.path.walk

Tim Roberts timr at probo.com
Sat Nov 30 00:38:53 EST 2002


martian_bob at portalofevil.com (R. Arens) wrote:
>
>Hi. I'm writing what should be a simple function that will walk a
>directory structure, opening and joining all files within the
>directory tree into a single huge file.
>...
>import os, sys
>
>def walkJoin(out, dirname, names):
>    print "Current directory: " + dirname
>    names.sort()
>    for name in names:
>        if os.path.isfile(name):
>            file = open(name, 'r')
>            lines = file.readlines()
>            for line in lines:
>                out.writeline(line)
>            file.close()
>        else:
>            print "Keep walking"
>            os.path.walk(name, walkJoin, out)

No, no, no!  "os.path.walk" is recursive all by itself.  It will keep
calling your callback with deeper and deeper directories.  You do NOT need
to call "walk" multiple times.

I suspect what you have here is a recipe for an infinite loop.
--
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list