我如何用Python找到脚本的目录?

这个问题在这里已经有了答案:

  • 如何正确确定当前脚本目录? 12个答案

  • 你需要在__file__上调用os.path.realpath ,这样当__file__是没有路径的文件名时,你仍然可以得到dir路径:

    import os
    print(os.path.dirname(os.path.realpath(__file__)))
    

    我用:

    import os
    import sys
    
    def get_script_path():
        return os.path.dirname(os.path.realpath(sys.argv[0]))
    

    正如aiham在评论中指出的那样,您可以在模块中定义此功能并将其用于不同的脚本中。


    尝试sys.path[0]

    引用Python文档:

    在程序启动时初始化,此列表中的第一项path[0]是包含用于调用Python解释器的脚本的目录。 如果脚本目录不可用(例如,如果解释器是交互式调用的,或者脚本是从标准输入中读取的), path[0]是空字符串,它指示Python首先搜索当前目录中的模块。 请注意,由于PYTHONPATH而插入的条目之前插入了脚本目录。

    来源:https://docs.python.org/library/sys.html#sys.path

    链接地址: http://www.djcxy.com/p/9289.html

    上一篇: How can I find script's directory with Python?

    下一篇: Print in terminal with colors?