recursive glob

Egor Bolonev ebolonev at front.ru
Mon Jun 23 03:12:25 CEST 2003


Hi all.

I have the recursive function glob(rec_glob), and I want to transform it
using yield
statement(get rid of lists - l and d).

yield func work incorrect an I can't fix it - please help me

Is there other implements for recursive glob?

===========================================
using lists
===========================================
def rec_glob_get_dirs(path):
    d=[]
    try:
        for i in os.listdir(path):
            if os.path.isdir(path+i):
                d.append(os.path.basename(i))
    except:pass
    return d

def rec_glob(path,mask):
    l=[]
    if path[-1]!='\\':
        path=path+'\\'
    for i in rec_glob_get_dirs(path):
        l=l+rec_glob(path+i,mask)
    try:
        for i in os.listdir(path):
            ii=i
            i=path+i
            if os.path.isfile(i):
                if fnmatch.fnmatch(ii,mask):
                    l.append(i)
    except:pass
    return l
===========================================


===========================================
using yield
===========================================
import os,fnmatch

def rec_glob_get_dirs(path):
    try:
        for i in os.listdir(path):
            if os.path.isdir(path+i):
                yield os.path.basename(i) # work ok
    except:pass

def rec_glob(path,mask):
    if path[-1]!='\\':
        path=path+'\\'
    for i in rec_glob_get_dirs(path):
        rec_glob(path+i,mask)
    try:
        for i in os.listdir(path):
            ii=i
            i=path+i
            if os.path.isfile(i):
                if fnmatch.fnmatch(ii,mask):
                    yield i # :-(
    except:pass

if __name__ == '__main__':
    f=open('log','wb')
    for i in rec_glob('C:\\python23\\lib','*'):
        f.write(i+'\n')
    f.close()
    print 'Done.'
    #while 1:pass
===========================================

--
    Egor






More information about the Python-list mailing list