返回所有parts.txt文件的路径列表 [英] Return a list of the paths of all the parts.txt files

查看:112
本文介绍了返回所有parts.txt文件的路径列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个函数list_files_walk,该函数使用os模块的walk生成器返回所有parts.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_filess_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仍然为空.输出应该看起来像这样:

Currently, list_files is still empty. The output is supposed to look similar to this:

CarItems/Chevrolet/Chevelle/2011/parts.txt
CarItems/Chevrolet/Chevelle/1982/parts.txt

如何产生此输出?

推荐答案

您几乎在这里拥有了-我唯一要做的调整是:

You pretty much have it here--the only adjustments I'd make are:

  • 确保list_files在本地作用域内,以避免副作用.
  • 使用参数,以便函数可以在任意路径上工作.
  • 使用yield关键字返回生成器,该生成器允许延迟获取下一个文件.
  • 如果文件名恰巧是路径中其他位置的子字符串,则
  • 'parts.txt' in dirpath可能容易出错.我会使用endswith或遍历元组中的第二个项目os.walk,这是当前目录中所有项目的列表,例如'parts.txt' in dirnames.
  • 沿着与上述相同的思路,您可能要确保目标是
  • 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 use endswith or iterate over the second item in the tuple that os.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.

这是一个例子:

import os

def find_files_rec(path, fname):
    for dirpath, dirnames, files in os.walk(path):
        if fname in files:
            yield f"{dirpath}/{fname}"

if __name__ == "__main__":
    print(list(find_files_rec(".", "parts.txt")))

这篇关于返回所有parts.txt文件的路径列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆