【问题标题】:How to get the path from content root in python?如何从python中的内容根目录获取路径?
【发布时间】:2023-01-12 19:58:24
【问题描述】:

假设我有一个名为 directory 1 的工作目录。该目录有一个 app.py 文件和一个名为 directory2 的目录文件。在 directory2 中,我有一个名为 example.txt 的文本文件。

有没有办法使用 app.py 中的命令找到 example.txt 的路径,只知道文本文件的名称并且它存在于我的工作目录的某个目录中?

【问题讨论】:

    标签: python directory


    【解决方案1】:

    OS.walk() 就是您所追求的。

    演示

    import os
    
    def find_file():
        for root, dirs, files in os.walk(os.getcwd()):
            if 'example.txt' in files:
                print('file exists')
                return
        print('file does not exist')
    
    find_file()
    

    【讨论】:

    • 这表明它存在。我如何找到这个文件的相对路径?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    相关资源
    最近更新 更多