pjc*_*c42 6 python ipython ipython-notebook
在IPython中,是否可以通过编程方式将工作目录设置为笔记本的目录?
例如,以下代码将在常规.py文件中工作.
import os
# show working dir
os.chdir(os.path.abspath('/'))
print "initial working directory:\t", os.getcwd()
# get path of script file
scriptPath = os.path.abspath(os.path.dirname(__file__))
# change working dir to dir with script file
os.chdir(scriptPath)
# show working directory
print "final working directory:\t", os.getcwd()
Run Code Online (Sandbox Code Playgroud)
但是,我找不到相当于的
__file__
Run Code Online (Sandbox Code Playgroud)
ipython nb文件的变量.是否有一些等效的ipynb文件方法?
iPython笔记本似乎会自动将目录切换到与.ipynb文件相同的目录.您想要更改该目录,然后稍后再更改吗?如果是这样,只需将原始目录存储在程序的开头并随时使用.
import os
orig_dir = os.getcwd()
os.chdir('/some/other/directory')
#do stuff
os.chdir(orig_dir)
Run Code Online (Sandbox Code Playgroud)
编辑:似乎有一个特殊变量_dh
,它是一个列表,_dh[0]
包含启动iPython内核的目录的名称.我只是发现了这个,所以我不确定这对于SaveAs来说是否也很健壮(我在我的iPython版本中找不到这样做的方法).但是,当我这样做时它不会改变os.chdir()
,所以我怀疑至少列表的第一个元素总是包含笔记本的目录.