Given search paths separated by a separator, find the first file that matches a given specification.
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
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.
Mitch Chapman
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'.
Another one. The abspath function is not imported. The first import statement should probably be 'from os.path import exists, join, abspath'.
Sometimes there are implicit extension on sought files. Here's a version that accommodates for implicit extensions (nice formatting system!)::
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