将目录作为字符串给出,如何找到其中是否存在任何文件?
os.path.isFile() # only accepts a specific file path
os.listdir(dir) == [] # accepts sub-directories
我的目标是检查路径是否仅缺少文件(也不是子目录)。
答案 0 :(得分:11)
要仅检查一个特定目录,这样的解决方案就足够了:
from os import listdir
from os.path import isfile, join
def does_file_exist_in_dir(path):
return any(isfile(join(path, i)) for i in listdir(path))
剖析正在发生的事情:
does_file_exist_in_dir
将走你的路。作为一个选项,如果你想遍历给定路径的所有子目录并检查文件,你可以使用os.walk并检查你所在的级别是否包含这样的文件:
for dir, sub_dirs, files in os.walk(path):
if not files:
print("no files at this level")