循环遍历特定文件目录中的文件。如果文件不存在,请将 "File not found" 附加到列表,否则附加文件位置

Loop through files in a directory for a particular file. If the file is not there, append a "File not found" to a list else append the file location

我在 excel sheet 中有一个文件名列表,我需要文件位置。我希望代码 运行 遍历指定目录中的所有文件,如果找到该文件,则将文件位置附加到列表中。如果找不到该文件,我希望它在列表中附加一个 "File not found" 。

如果文件确实存在,我的代码就可以工作,但是,当文件不存在时,我似乎找不到解决问题的方法。我试过:

if name not in file:
   file_location.append("File Not Found")

但是它所做的是为它循环的每个文件附加一个 "File Not Found"。

def file_loc(basedir, filename):
    """Searches through the directory for a particular file and then saves that path into a list"""
    for root, dirs, files in os.walk(basedir):
        for name in files:
            if filename in name:
                location = os.path.abspath(os.path.join(root, name))
                file_location.append(location)

我想要一个列表,打印出列表中文件的所有文件位置,如果找不到文件位置,列表应包含 "File Not Found"。因此,例如,如果我要搜索的文件是 [foo, bar, soap] 而 soap 文件不在我的目录中,它将打印出:

[File/path/to/foo, File/path/to/bar, "File Not Found"]

如有任何帮助,我们将不胜感激!

问题是您正在检查特定文件名是否匹配,并且您想知道是否匹配。如果在 运行 遍历所有 none 匹配的文件之后,则可以说未找到。所以我建议使用布尔变量来查看是否找到它。然后在循环完成后检查并在必要时追加。它应该看起来像这样。

def file_loc(basedir, filename):
"""Searches through the directory for a particular file and then saves that path into a list"""
found = false
for root, dirs, files in os.walk(basedir):
    for name in files:
        if filename in name:
            location = os.path.abspath(os.path.join(root, name))
            file_location.append(location)
            found = True
if not found:
  file_location.append("File Not Found")