Quote:
hi i was wondering if its possible to have pygtk .get_text() specify a filename for os.walk() to find while its traversing the directory tree?
|
This is not only possible but really quite simple to achieve.
I have supplied a little function called locate which you may import from it's module and utilize to return the files found that match the pattern supplied beneath the root directory also supplied. It works by first running os.walk down from the root, getting the files returned and filtering the list with the fnmatch pattern matching module. You may supply a full filename rather than a pattern and this will work too. Note that locate is a generator, a special kind of function, and so may be used in list comprehensions to build a list or "for loops " to iterate through the returned results. Also note I have supplied default parameters so you may call locate without passing anything and it will find all files below the current directory. It may seem unusual to import modules inside a function like this rather than at the head of a module but I have done this so the locate function may be imported directly from it's module and still work. If I performed the imports external to the locate function this would not be possible. As it is locate will return all examples when iterated over that it finds in or below the root directory but if you just want the first found then it's simple to process the first found in the for loop and then break to leave the loop as I do in the example.
Code:
def locate(pattern="*", root=None):
'''Locate all files matching supplied filename pattern in and below
supplied root directory.'''
import os, fnmatch
if root==None:
root=os.curdir
for path, dirs, files in os.walk(os.path.abspath(root)):
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
if __name__=="__main__":
myfilepattern="*.py" # pattern to match - change to suit
myrootdir="/home/ed/source/python" # root dir - this should be changed to suit
for names in locate(myfilepattern, myrootdir):
print names
break # just get first found for this example
mylist=[names for names in locate(myfilepattern, myrootdir)] # try a list comprehension
print mylist
It's a simple job to tie in your pygtk code calling get_text to return a filename or pattern and slot this into locate. Also note the locate function is only seven lines of code and so offers little additional code complexity. The majority of the code is just there to test stuff out, offer examples and document.