문제

I started with some code I got from another stackoverflow question 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.

도움이 되었습니까?

해결책

How about?

result = [os.path.join(root, file) for root, dir, files in os.walk(mydir) for file in files]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top