Python 如何检查不同目录中是否存在多个文件

Python 如何检查不同目录中是否存在多个文件,python,io,Python,Io,我知道如何使用python检查文件是否存在,但我要做的是尝试查看在我的工作目录中是否存在多个同名文件。例如: gamedata/areas/ # i have 2 folders in this directory # testarea and homeplace 1. gamedata/areas/testarea/ 2. gamedata/areas/homeplace/ 例如,homeplace和testarea的每个文件夹都包含一个名为“示例”的文件 是否有一种类似pythoni

我知道如何使用python检查文件是否存在,但我要做的是尝试查看在我的工作目录中是否存在多个同名文件。例如:

gamedata/areas/ 
# i have 2 folders in this directory
# testarea and homeplace


1. gamedata/areas/testarea/
2. gamedata/areas/homeplace/
例如,homeplace和testarea的每个文件夹都包含一个名为“示例”的文件

是否有一种类似pythonic的方法来使用“os”或类似的工具来检查文件“example”是否可以在testarea和homeplace中找到

虽然它们是一种不用手动和静态使用

os.path.isfile()
因为在程序的整个生命周期中,都会生成新的目录,我不想不断地回到代码中去更改它。

可能类似于

places = ["testarea", "homeplace"]
if all(os.path.isfile(os.path.join("gamedata/areas/", x, "example") for x in places)):
    print("Missing example")

如果条件为false,则不会告诉您哪个子目录不包含文件
示例
。您可以根据需要更新
位置。

您可以在下面的每个目录下查看
游戏数据/区域/
: 这只会降低一个级别,您可以扩展它以降低任意多个级别

from os import listdir
from os.path import isdir, isfile, join
base_path = "gamedata/areas/"
files = listdir(base_path)
only_directories = [path for path in files if isdir(join(base_path,path))]

for directory_path in only_directories:
    dir_path = join(base_path, directory_path)
    for file_path in listdir(dir_path):
        full_file_path = join(base_path, dir_path, file_path)
        is_file = isfile(full_file_path)
        is_example = "example" in file_path
        if is_file and is_example:
            print "Found One!!"

希望有帮助

正如我在评论中提到的,
os.walk
是你的朋友:

import os

ROOT="gamedata/areas"
in_dirs = [path for (path, dirs, filenames)
                 in os.walk(ROOT)
                 if 'example' in filenames]

在_dirs中
将是一个子目录列表,在那里可以找到
示例

我相信你想看看
os.walk
或者(甚至更好)到
os.path.walk
完美我会试一试,我不在乎知道它在哪里,只要它存在就行。任意深度。请注意,
os.walk
如果您不告诉它,它将不会跟随符号链接(阅读文档)