flask框架,查询某个目录下文件列表,目录列表,查询是否存在某个文件

# 要查询的目录
    directory = '/path/to/directory'
    # 获取目录下的所有文件和目录
    contents = os.listdir(directory)
    # 筛选出所有的文件
    files = [os.path.join(directory, f) for f in contents if os.path.isfile(os.path.join(directory, f))]
    # 筛选出所有的目录
    directories = [os.path.join(directory, f) for f in contents if os.path.isdir(os.path.join(directory, f))]
    # 检查某个文件是否存在
    filename = 'example.txt'
    filepath = os.path.join(directory, filename)
    exists = os.path.isfile(filepath)

首先定义了要查询的目录 directory,然后使用 os.listdir() 方法获取目录下的所有文件和目录。我们使用列表推导式筛选出所有的文件和目录,其中 os.path.isfile()os.path.isdir() 方法用于判断某个路径是否为文件或目录。最后,我们使用 os.path.join() 方法来拼接目录和文件名,得到某个文件的完整路径,并使用 os.path.isfile() 方法检查该文件是否存在。

注意,上述代码中使用的路径是绝对路径,如果要使用相对路径,则需要使用 Flask 应用的根目录和 os.path.abspath() 方法将相对路径转换为绝对路径。

directory = os.path.join(app.root_path, 'path', 'to', 'directory')
directory = os.path.abspath(directory)

更多关于 Python os 模块和 os.path 模块的信息可以参考官方文档:https://docs.python.org/3/library/os.htmlhttps://docs.python.org/3/library/os.path.html

posted @ 2023-03-19 13:09  study_php_java_C++  阅读(285)  评论(0编辑  收藏  举报