os.path.walk() question.
jschmitt at vmlabs.com
jschmitt at vmlabs.com
Tue Apr 25 20:04:51 EDT 2000
I came up with this. Critique welcome!
##--FindFile.py
import os
import sys
import fnmatch
#-----------------------------------------------------------------------
--------------------------
class FoundFileException:
def __init__( self, fullname ):
self.fullname = fullname
#-----------------------------------------------------------------------
--------------------------
def callbackfunc( filename, dir, names ):
for name in names:
if fnmatch.fnmatch( name, filename ):
fullname = os.path.abspath( os.path.join( dir,
name ) )
raise FoundFileException( fullname )
# - raising an exception forces the search to
stop as soon as any match
# is found
#-----------------------------------------------------------------------
--------------------------
def FindFile( filename, dir=os.getcwd() ):
foundfile = None
try:
os.path.walk( dir, callbackfunc, filename )
except FoundFileException, filefound:
foundfile = filefound.fullname
return foundfile
#-----------------------------------------------------------------------
--------------------------
if __name__ == '__main__':
# if no directory is passed in, assume the current directory
if ( len(sys.argv) < 3 ):
directory = os.getcwd()
else:
directory = sys.argv[2]
fullname = FindFile( sys.argv[1], directory )
if fullname != None:
print fullname
else:
print sys.argv[1], 'is not in', os.path.abspath(
directory )
#-end of file
John
PS Hopefully deja.com doesn't mess up or wrap my posting.
In article <8e55m0$pvl$1 at hammer.msfc.nasa.gov>,
"Andrew McDowell" <drew.mcdowell at msfc.nasa.gov> wrote:
> I didn't see this question mentioned in any older posts so forgive me
if I'm
> dragging up and old topic...but:
>
> I need to find out if a file exists under a directory hierarchy.
> The hierarchy could be quite large so I don't want to continue
recursing
> through the hierarchy if the file is found one or two directories
down. Is
> there a way that you can tell os.path.walk() to stop searching?
>
> I suppose I could customize the code, but my first notion was that
someone
> on the group had probably addressed this before.
>
> Any advice would be much appreciated :)
>
> -Drew
>
>
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list