简体   繁体   中英

Create a list of all files in directory and subdirectories in python

I would like to come up with the most optimal way of listing all files in a directory and its subdirectories. Once done, I would like to filter them down. So, optimally this would be done in 2 lines:

def getFilesContaining(filename):
    files = map(lambda x: os.path.join(x, file), os.walk('.')) #Note: this map does NOT work
    filtered_files = filter(lambda x: filename in x, files)
    return filtered_files 
def getFilesContaining(filename):
    paths = (os.path.join(root, f) for root, dirs, files in os.walk('.')
             for f in files) 
    return (path for path in paths if filename in path)

This returns an iterator. In your version, filter returns a list. If you really want a list, change the return value into a list comprehension by replacing the outer parentheses (...) into brackets [...] .

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