简体   繁体   中英

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)
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM