如何检查多个文件在不同目录中是否存在
我知道怎么用Python检查一个文件是否存在,但我想知道的是,如何检查在我的工作目录中是否存在多个同名的文件。比如说:
gamedata/areas/
# i have 2 folders in this directory
# testarea and homeplace
1. gamedata/areas/testarea/
2. gamedata/areas/homeplace/
在homeplace和testarea这两个文件夹里,都有一个叫做'example'的文件。
有没有什么Python的方法,比如用'os'模块,来检查'example'这个文件是否同时在testarea和homeplace这两个地方都能找到呢?
另外,有没有办法做到这一点,而不需要手动和静态地使用
os.path.isfile()
因为在程序运行的过程中会不断创建新的目录,我不想每次都回去修改代码。
3 个回答
0
也许可以像这样写:
places = ["testarea", "homeplace"]
if all(os.path.isfile(os.path.join("gamedata/areas/", x, "example") for x in places)):
print("Missing example")
如果条件是假的,这段代码并没有告诉你哪个子目录里没有这个文件example
。你可以根据需要更新places
。
0
正如我在评论中提到的,os.walk
是一个很有用的工具:
import os
ROOT="gamedata/areas"
in_dirs = [path for (path, dirs, filenames)
in os.walk(ROOT)
if 'example' in filenames]
in_dirs
将会是一个包含找到 example
的所有子目录的列表。
1
你可以查看在 gamedata/areas/
目录下的每一个文件夹:
这个方法只会往下查找一层,如果你想查找更多层级的文件夹,也可以把它扩展到你想要的层数。
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!!"
希望这对你有帮助!