返回所有parts.txt文件的路径列表 [英] Return list of the paths of all the parts.txt files
问题描述
编写一个函数list_files_walk,该函数使用os模块的walk生成器返回所有part.txt文件的路径的列表.该函数不使用任何输入参数.
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
输出(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
如何产生此输出?
推荐答案
您已经关闭.出于某种原因,您在filenames
中搜索parts.txt
时应该在filenames
中进行搜索:
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
我使用endswith
是因为它比问"parts.txt"是否在文件名in
处更准确,但是在大多数情况下也可以:
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
这篇关于返回所有parts.txt文件的路径列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!