0

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 
4

1 に答える 1

3
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)

これは反復子を返します。お使いのバージョンでfilterは、リストを返します。(...)本当にリストが必要な場合は、外側の括弧を角かっこに置き換えて、戻り値をリスト内包表記に変更します[...]

于 2012-09-18T00:32:13.853 に答える