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 @   study_php_java_C++  阅读(404)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示