newb question: file searching

Jason tenax.raccoon at gmail.com
Tue Aug 8 16:58:25 EDT 2006


jaysherby at gmail.com wrote:
> Mike Kent wrote:
> > What you want is os.walk().
> >
> > http://www.python.org/doc/current/lib/os-file-dir.html
>
> I'm thinking os.walk() could definitely be a big part of my solution,
> but I need a little for info.  If I'm reading this correctly, os.walk()
> just goes file by file and serves it up for your script to decide what
> to do with each one.  Is that right?  So, for each file it found, I'd
> have to decide if it met the criteria of the filetype I'm searching for
> and then add that info to whatever datatype I want to make a little
> list for myself?  Am I being coherent?
>
> Something like:
>
> for files in os.walk(top, topdown=False):
>     for name in files:
>          (do whatever to decide if criteria is met, etc.)
>
> Does this look correct?

Not completely.  According to the documentation, os.walk returns a
tuple:
  (directory, subdirectories, files)
So the files you want are in the third element of the tuple.

You can use the fnmatch module to find the names that match your
filename pattern.

You'll want to do something like this:

>>> for (dir, subdirs, files) in os.walk('.'):
...  for cppFile in fnmatch.filter(files, '*.cpp'):
...   print cppFile
...
ActiveX Test.cpp
ActiveX TestDoc.cpp
ActiveX TestView.cpp
MainFrm.cpp
StdAfx.cpp
>>>

Please note that your results will vary, of course.




More information about the Python-list mailing list