问题
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_files_walk():
for dirpath, dirnames, filenames in os.walk("CarItems"):
if 'parts.txt' in dirpath:
list_files.append(filenames)
print(list_files)
return list_files
The output (list_files) is supposed to look similar to this:
CarItems/Chevrolet/Chevelle/2011/parts.txt
CarItems/Chevrolet/Chevelle/1982/parts.txt
How can I produce this output?
回答1:
You were close. You're searching for parts.txt
in dirpath
for some reason when you should be searching it in filenames
:
def list_files_walk():
results = []
for dirpath, dirnames, filenames in os.walk("CarItems"):
for f in filenames:
if f.endswith('parts.txt'):
results.append(os.path.join(dirpath, f))
return results
I use endswith
because it is more accurate than just asking if "parts.txt" is somewhere in
the filename, but that would also work in most cases:
def list_files_walk():
results = []
for dirpath, dirnames, filenames in os.walk("CarItems"):
for f in filenames:
if 'parts.txt' in f:
results.append(os.path.join(dirpath, f))
return results
来源:https://stackoverflow.com/questions/59015762/return-list-of-the-paths-of-all-the-parts-txt-files