Change directory to the directory of a Python script

How do i change directory to the directory with my python script in? So far I figured out I should use os.chdir and sys.argv[0] . I'm sure there is a better way then to write my own function to parse argv[0].


os.chdir(os.path.dirname(__file__))

有时__file__没有定义,在这种情况下,你可以尝试sys.path[0]


os.chdir(os.path.dirname(os.path.abspath(__file__))) should do it.

os.chdir(os.path.dirname(__file__)) would not work if the script is run from the directory in which it is present.

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

上一篇: 我如何在C中找到可执行文件的位置?

下一篇: 将目录切换到Python脚本的目录