Return A List Of The Paths Of All The Parts.txt Files
Write a function list_files_walk that returns a list of the paths of all the parts.txt files, using the os module's walk generator. The function takes no input parameters. def list
Solution 1:
You pretty much have it here--the only adjustments I'd make are:
- Make sure
list_files
is scoped locally to the function to avoid side effects. - Use parameters so that the function can work on any arbitrary path.
- Return a generator with the
yield
keyword which allows for the next file to be fetched lazily. 'parts.txt' in dirpath
could be error-prone if the filename happens to be a substring elsewhere in a path. I'd useendswith
or iterate over the second item in the tuple thatos.walk
which is a list of all the items in the current directory, e.g.'parts.txt' in dirnames
.- Along the same line of thought as above, you might want to make sure that your target is a file with
os.path.isfile
.
Here's an example:
import os
deffind_files_rec(path, fname):
for dirpath, dirnames, files in os.walk(path):
if fname in files:
yieldf"{dirpath}/{fname}"if __name__ == "__main__":
print(list(find_files_rec(".", "parts.txt")))
Post a Comment for "Return A List Of The Paths Of All The Parts.txt Files"