gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:53:56 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com