Return list of the paths of all the parts.txt files

爱⌒轻易说出口 提交于 2019-12-02 14:26:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!