liv2hak liv2hak - 5 months ago 10
Python Question

getting filename from python generator object

I am new to python. I am learning os.walk and yield. If I try to

print(fname)
below it prints a generator object. How do I print the actual file name generated.

import os, fnmatch

def locate(pattern, root=os.curdir):

for path, dirs, files in os.walk(os.paths.abspath(root)):
for filename in fnmatch.filter(files,pattern):
yield os.path.join(path,filename)


if __name__ == '__main__':
fname = locate('assert.py')
print(fname)

Answer
if __name__ == '__main__':
    for fname in locate('assert.py')
        print(fname)

generators are not evaluated until needed (or iterated)

print next(locate("assert.py"),"assert.py not found!")

is a way to just get the first match