How can I search sub-folders using glob.glob module in Python?
Question: I want to open a series of subfolders in a folder and find some text files and
print some lines of the text files. I am using this:

    
    
    configfiles = glob.glob('C:/Users/sam/Desktop/file1/*.txt")
    

But this cannot access the subfolders as well. Does anyone know how I can use
the same command to access subfolders as well?


Answer: Current versions of `glob.glob()` cannot list files in subdirectories
recursively (an [update that will be included in python 3.5 when
released](http://bugs.python.org/issue13968) adds a `**` option for arbitrary
nested directory traversal).

I'd use [`os.walk()`](http://docs.python.org/2/library/os.html#os.walk)
combined with
[`fnmatch.filter()`](http://docs.python.org/2/library/fnmatch.html#fnmatch.filter)
instead:

    
    
    import os
    import fnmatch
    
    path = 'C:/Users/sam/Desktop/file1'
    
    configfiles = [os.path.join(dirpath, f)
        for dirpath, dirnames, files in os.walk(path)
        for f in fnmatch.filter(files, '*.txt')]
    

This'll walk your directories recursively and return all absolute pathnames to
matching `.txt` files. In this _specific_ case the `fnmatch.filter()` may be
overkill, you could also use a `.endswith()` test:

    
    
    import os
    
    path = 'C:/Users/sam/Desktop/file1'
    
    configfiles = [os.path.join(dirpath, f)
        for dirpath, dirnames, files in os.walk(path)
        for f in files if f.endswith('.txt')]
    

