[Pythonmac-SIG] Stupid OS.WALK tricks?
Dinu Gherman
gherman@darwin.in-berlin.de
Tue, 13 Nov 2001 18:01:35 +0100 (CET)
"Schollnick, Benjamin" <Benjamin.Schollnick@usa.xerox.com>:
> Folks,
>
> I'm attempting to optimize a quick program, but os.walk
> is sort of interferring...
>
> I'm searching a directory tree for graphic file.... using
> os.walk, and when it finds the file, it copies it to a local
> directory...
>
> The "problem" here, is that I can't figure out how to
> stop OS.walk (in the visit function) from "continuing"
> through the rest of the directories, and to just move
> on to the next file... (There should only be one match)..
>
> I figure I'm going to have to write a custom walk to
> deal with this scenario.... Does anyone have anything
> similiar? Or suggestions on dealing with this?
>
> Doing a "return" or "Break" during the search doesn't seem
> to do this....
>
> - Benjamin
Not exactly a Mac issue, but how about this code written by
/F that you can extend as you like with filters, etc (have
not bothered to remove all unneeded imports):
"""
import os, sys, glob, fnmatch, string
from os.path import basename, dirname, join, islink, isdir, isfile
# Convenience class, as suggested by /F.
class GlobDirectoryWalker:
"A forward iterator that traverses files in a directory tree."
def __init__(self, directory, pattern="*"):
self.stack = [directory]
self.pattern = pattern
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = join(self.directory, file)
if isdir(fullname) and not islink(fullname):
self.stack.append(fullname)
if fnmatch.fnmatch(file, self.pattern):
return fullname
files = GlobDirectoryWalker(f)
for file in files:
handle(file) # not implemented
"""
I know os.walk can make you bang your head against the wall in
unexpected ways...
Dinu
--
Dinu C. Gherman
................................................................
"They made a desert and called it peace." (Tacitus)