Your function could be a generator (which were introduced in Python 2.2). It should also expose the pattern for the filter as a parameter:
import os
import fnmatch
def files_within(directory_path, pattern="*"):
for dirpath, dirnames, filenames in os.walk(directory_path):
for file_name in fnmatch.filter(filenames, pattern):
yield os.path.join(dirpath, file_name)
if __name__ == "__main__":
# You can simply iterate over the generator:
for file_path in files_within("."):
print file_path
# If you absolutely need a list:
file_list = list(files_within("../"))
# Use the pattern parameter:
text_files = list(files_within(".", "*.txt"))
I like to leave the names from os.walk
the same as in the documentation, but this is a personal choice.
What is not quite a personal choice is the number of tabs per indentation level. Python's official style-guide, PEP8, recommends using always 4 spaces.
I also changed the way of the imports. Here it already becomes obvious why importing them like this is better (as far as readability goes). It is obvious that fnmatch.filter
is from the module fnmatch
and not the built-in filter
.