[英]Spyder/Python - Automatically set working directory to current script's
I know that the directory can be automatically changed to that of the current script if we press F5.我知道如果我们按 F5,目录可以自动更改为当前脚本的目录。
But is there a way to automatically do so when I run the codes in interactive mode, or when I open a script?但是,当我以交互模式运行代码或打开脚本时,有没有办法自动执行此操作? Currently I need to os.chdir() to the current working directory.
目前我需要 os.chdir() 到当前工作目录。
Thanks.谢谢。
You can add the following lines to your script:您可以将以下行添加到您的脚本中:
import os
os.chdir(os.path.dirname(__file__))
__file__
will return the path of the script, and we can use os.path.dirname
to find which directory it is located in. Then just use os.chdir
to change to that directory. __file__
将返回脚本的路径,我们可以使用os.path.dirname
找到它所在的目录。然后只需使用os.chdir
切换到该目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.