如何将目录更改为包含 Python 脚本的目录?到目前为止,我发现我应该使用
os.chdir
和 sys.argv[0]
。我确信有更好的方法来编写我自己的函数来解析 argv[0]。
os.chdir(os.path.dirname(__file__))
os.chdir(os.path.dirname(os.path.abspath(__file__)))
应该这样做。
如果脚本从其所在的目录运行,os.chdir(os.path.dirname(__file__))
将不起作用。
有时
__file__
未定义,这种情况你可以尝试sys.path[0]
在 Windows 操作系统上,如果您调用类似 python somefile.py 的内容,则 os.chdir(os.path.dirname(__file__)) 将抛出 WindowsError。但这应该适用于所有情况:
import os
absFilePath = os.path.abspath(__file__)
os.chdir( os.path.dirname(absFilePath) )
import os
if __name__ == "__main__": # import this_file will not change cwd
os.chdir(os.path.dirname(__file__))