Iterating through individual files in os.walk in Python in an idiomatic fashion
Question: I started with some code I got from [another stackoverflow
question](http://stackoverflow.com/questions/2865278/in-python-how-to-find-
all-the-files-under-a-directory-including-the-files-in-s/2865328#2865328) to
generate full paths for all the files in a directory tree:

    
    
    import os
    def recursive_file_gen(mydir):
        for root, dirs, files in os.walk(mydir):
            for file in files:
                yield os.path.join(root, file)
    

I wanted to add memoization, and it seemed to me the easiest way to achieve
was just to make recursive_file_gen return a list instead:

    
    
    def recursive_file_list(mydir):
        result = []
        for root, dirs, files in os.walk(mydir):
            for file in files:
                result.append(os.path.join(root, file))
        return result
    

This code is fine, really. It's certainly not hard to figure out what's going
on. But putting together a list using successive `append` operations isn't
fully Pythonic. My guess is there's a better way using Python syntax, probably
via a list comprehension, and learning it would be edifying.

Of course I could write:

    
    
    def recursive_file_list(mydir):
        return list(recursive_file_gen(mydir))
    

and memoize that. But I'm wondering if there's anything cleaner.


Answer: How about?

    
    
    result = [os.path.join(root, file) for root, dir, files in os.walk(mydir) for file in files]
    

