【问题标题】:Query current directory in Python (the one the script is running from)在 Python 中查询当前目录(运行脚本的目录)
【发布时间】:2014-04-07 18:14:41
【问题描述】:

有什么方法可以在我们想知道位置的脚本中查询脚本的绝对路径吗?例如,如果我将它保存在我的桌面上,我想将绝对位置存储到一个变量中,我希望它返回 C:/Users/Doc/Desktop

我在另一个人的脚本中看到了这段代码,但我不知道它是否对我的目标有用:path = os.path.dirname(script.__file__)

你知道如何实现吗?提前致谢。

【问题讨论】:

    标签: python path directory location


    【解决方案1】:

    要获取当前脚本的路径,请使用:

    __file__
    

    要从中获取目录:

    os.path.dirname(__file__)
    

    要获取当前工作目录(脚本运行时所在的目录),请使用:

    os.getcwd()
    

    os.getcwd documentation

    【讨论】:

      【解决方案2】:

      是的,__file__ 就是您要找的;但它可以是相对路径。

      用途:

      here = os.path.basename(os.path.abspath(__file__))
      

      把它变成脚本所在位置的目录路径。 os.path.abspath() 取一个相对路径并将其转为绝对路径(以当前工作目录为参考); os.path.dirname() 从该路径中分离出文件名。

      【讨论】:

        猜你喜欢
        • 2019-02-10
        • 2023-01-12
        • 1970-01-01
        • 2013-06-26
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 2012-04-11
        相关资源
        最近更新 更多