Get the filenames in a directory and its subdirectories

Egor Bolonev ebolonev at mail.ru
Sun Jun 29 17:37:57 EDT 2003


> That would be very handy for a small progrtam I've written. I've
> browsed through the documentation for the standard modules but
> there doesn't seem to be a way (please correct me if I'm wrong).
>
> I know that it shouldn't be very hard to write a module myself
> using listdir() and isdir() or stuff like that, but I'm having
> problems.

There are a my funcs (for Windows):


===========================================
def rec_glob(path,mask)
def rec_glob(mask)
===========================================
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)
    except:pass


def rec_glob(path,mask):
    p=[]
    if len(path)<>0:
        if path[-1]!='\\':
            path=path+'\\'
    for i in rec_glob_get_dirs(path):
        for ii in rec_glob(path+i,mask):
            yield ii
    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


def rec_glob(mask):
    rec_glob('',mask)



if __name__ == '__main__':
    f=open('log','wb')
    for i in rec_glob('E:','*'):
        f.write(i+'\n')
    f.close()


    print 'Done.'
    #while 1:pass
===========================================

and

===========================================
import os,fnmatch

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 len(path)<>0:
        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

def rec_glob(mask):
    rec_glob('',mask)



if __name__ == '__main__':
    f=open('log','wb')
    for i in rec_glob('C:\\','*'):
        f.write(i+'\n')
    f.close()


    print 'Done.'
    #while 1:pass
===========================================







More information about the Python-list mailing list