Better way to searching.

David Tweet davidtweet at gmail.com
Fri Dec 14 03:38:58 EST 2007


Hello,
  You might try using os.path.walk, I think it ends up being much
more flexible than glob for this.

#!/usr/bin/python2.4

import os

def Finder(topdir, file_extension=None, levels=None):
  """Return all filenames in topdir.
  Args:
    topdir:  Top level directory to search
    file_extension:  file extension to match on
    levels:  number of directory levels to search
  Returns:
    list of file names.
  """

  def Levels(pathname):
    return pathname.count(os.path.sep)

  if levels is not None:
    pathlevels_allowed = Levels(topdir) + levels

  def WalkFunction(accumulator, dir, filenames):
    """Called from os.path.walk; accumulate matching filenames.
    Args:
      accumulator:  list we are adding files to
      dir:  directory being traversed
      filenames:  list of files in dir
    Returns:
      None
    Modifies:
      filenames, if we want to stop descending.
    """
    if levels is not None:
      if Levels(dir) > pathlevels_allowed:
        del filenames[:]
        return
    if file_extension is not None:
      accumulator.extend(os.path.join(dir, f) for f in filenames
                         if os.path.splitext(f)[1] == file_extension)
    else:
      accumulator.extend(os.path.join(dir, f) for f in filenames)

  acc = []
  os.path.walk(topdir, WalkFunction, acc)

  return acc

if __name__ == '__main__':
  files = Finder("/your/starting/directory", file_extension=".mpg", levels=2)
  print files




On Dec 13, 2007 11:13 PM, farsheed <rodmena.com at gmail.com> wrote:
> my code is here:
>
> _________________________________________________________________________
>
>         def Globing(self, dir, extension, nop, inputDepth):
>                 'It creates a basic glob function that needed in other classes'
>                 self.exop = '*.'
>                 self.opr = '*/'
>                 self.counter = ''
>                 self.files = []
>                 self.path = ''
>                 for i in range (inputDepth):
>                         self.path = dir + self.opr * i + self.exop * nop + extension
> #like this:        */*/*.*.mpg
>                         self.counter = glob.glob(self.path)
>                         self.files += self.counter
>                 return self.files
> ____________________________________________________________________________
>
> Is there any better and faster way to do this?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
-David



More information about the Python-list mailing list