Python:检查给定目录中是否存在任何文件

标签 python file path directory

给定一个字符串形式的目录,我如何查找其中是否存在任何文件?

os.path.isFile()       # only accepts a specific file path
os.listdir(dir) == []  # accepts sub-directories

我的目标是检查路径是否仅缺少文件(也不是子目录)。

最佳答案

只检查一个特定的目录,这样的解决方案就足够了:

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 方法将采用您的路径。
  • 使用any如果通过调用 listdir 遍历路径内容找到文件,它将返回 True在上面。注意 join 的使用对于路径,以便提供合格的文件路径名称以进行正确检查。

作为一个选项,如果你想遍历给定路径的所有子目录并检查文件,你可以使用os.walk。然后检查你所在的关卡是否包含这样的文件:

for dir, sub_dirs, files in os.walk(path):
    if not files:
        print("no files at this level")

关于Python:检查给定目录中是否存在任何文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33463325/

相关文章:

Python:将以特定行为边界的 block 复制到新文件

java - 如何将InputStream对象转换为File对象?

python - 如何在Python中根据多个其他列表过滤列表?

python - 当对象处于事件状态时,lxml 对象标识符似乎会被重用

Java解析具有不同工作目录的文件路径

html - 如何在 Angular2 中提供图像?

python - 如何从代码配置 nltk 数据目录?

c# - 在 Mono C# CLI 应用程序中获取包的路径

python - 具有特定空白的大括号之前的字符串的正则表达式

python - numpy polyfit 中使用的权重值是多少,拟合误差是多少