将目录更改为Python脚本的目录

问题描述 投票:0回答:5

如何将目录更改为包含 Python 脚本的目录?到目前为止,我发现我应该使用

os.chdir
sys.argv[0]
。我确信有更好的方法来编写我自己的函数来解析 argv[0]。

python scripting directory
5个回答
34
投票
os.chdir(os.path.dirname(__file__))

17
投票

os.chdir(os.path.dirname(os.path.abspath(__file__)))
应该这样做。

如果脚本从其所在的目录运行,

os.chdir(os.path.dirname(__file__))
将不起作用。


7
投票

有时

__file__
未定义,这种情况你可以尝试
sys.path[0]


2
投票

在 Windows 操作系统上,如果您调用类似 python somefile.py 的内容,则 os.chdir(os.path.dirname(__file__)) 将抛出 WindowsError。但这应该适用于所有情况:

import os
absFilePath = os.path.abspath(__file__)
os.chdir( os.path.dirname(absFilePath) )

0
投票
import os
if __name__ == "__main__": # import this_file will not change cwd
    os.chdir(os.path.dirname(__file__))
© www.soinside.com 2019 - 2024. All rights reserved.