ActiveState Code

Recipe 52224: Find a file given a search path


Given search paths separated by a separator, find the first file that matches a given specification.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from os.path import exists, join
from os import pathsep
from string import split

def search_file(filename, search_path):
   """Given a search path, find file
   """
   file_found = 0
   paths = string.split(search_path, pathsep)
   for path in paths:
      if exists(join(path, filename)):
          file_found = 1
          break
   if file_found:
      return abspath(join(path, filename))
   else:
      return None

if __name__ == '___main__':
   search_path = '/bin' + pathsep + '/usr/bin'  # ; on windows, : on unix
   find_file = search_file('ls',search_path)
   if find_file:
      print "File found at %s" % find_file
   else:
      print "File not found"

Comments

  1. 1. At 3:23 p.m. on 15 mar 2001, Mitch Chapman said:

    Variation: Finding files on the Python path. Larger Python applications consist of sets of Python packages and associated sets of "resource" files (e.g. Glade project files, SQL templates, image files). It's convenient to store these associated files together with the Python packages which use them. It's easy to do so if you use a variation on this recipe, one which finds files relative to the Python path.

    #!/usr/bin/env python
    import sys, os
    
    class Error(Exception): pass
    
    def _find(path, matchFunc=os.path.isfile):
        for dirname in sys.path:
            candidate = os.path.join(dirname, path)
            if matchFunc(candidate):
                return candidate
        raise Error("Can't find file %s" % path)
    
    def find(path):
        return _find(path)
    
    def findDir(path):
        return _find(path, matchFunc=os.path.isdir)
    

    Mitch Chapman

  2. 2. At 7:32 a.m. on 16 jan 2004, Phil Rittenhouse said:

    Small correction. The call to string.split(), in the search_file() function, should just be a call to split() since the example uses 'from string import split'.

  3. 3. At 7:44 a.m. on 16 jan 2004, Phil Rittenhouse said:

    Another one. The abspath function is not imported. The first import statement should probably be 'from os.path import exists, join, abspath'.

  4. 4. At 11:14 a.m. on 7 nov 2005, Micah Elliott said:

    Sometimes there are implicit extension on sought files. Here's a version that accommodates for implicit extensions (nice formatting system!)::

    def findFile(seekName, path, implicitExt=''):
        """Given a pathsep-delimited path string, find seekName.
        Returns path to seekName if found, otherwise None.
        Also allows for files with implicit extensions (eg, .exe), but
        always returning seekName as was provided.
        >>> findFile('ls', '/usr/bin:/bin', implicitExt='.exe')
        '/bin/ls'
        """
        if (os.path.isfile(seekName)
              or implicitExt and os.path.isfile(seekName + implicitExt)):
            # Already absolute path.
            return seekName
        for p in path.split(os.pathsep):
            candidate = os.path.join(p, seekName)
            if (os.path.isfile(candidate)
                  or implicitExt and os.path.isfile(candidate + implicitExt)):
                return candidate
        return None
    
  5. 5. At 8:17 p.m. on 29 jun 2007, Alejandro Decchi said:

    Hello. Hi! I try to use this search code :

    !/usr/bin/python

    from os.path import exists, join from os import pathsep from string import split

    def search_file(filename, search_path): """Given a search path, find file """ file_found = 0 paths = string.split(search_path, pathsep) for path in paths: if exists(join(path, filename)): file_found = 1 break if file_found: return abspath(join(path, filename)) else: return None

    if __name__ == '___main__': search_path = '/bin' + pathsep + '/usr/bin' # ; on windows, : on unix find_file = search_file('ls',search_path) if find_file: print "File found at %s" % find_file else: print "File not found

    But where i must put the word to search ???? and How can i do to download the file found ???

Sign in to comment