__file__ does not exist in Jupyter Notebook

前端 未结 4 1750
无人及你
无人及你 2020-12-23 18:54

I\'m on a Jupyter Notebook server (v4.2.2) with Python 3.4.2 and I want to use the global name __file__, because the notebook will be cloned from other users an

4条回答
  •  有刺的猬
    2020-12-23 19:11

    If you want to get path of the directory in which your script is running, I would highly recommend using,

    os.path.abspath('')
    

    Advantages

    • It works from Jupyter Notebook
    • It work from REPL
    • It doesn't require Python 3.4's pathlib

    Please note that one scenario where __file__ has advantage is when you are invoking python from directory A but running script in directory B. In that case above as well as most other methods will return A, not B. However for Jupyter notbook, you always get folder for .ipyn file instead of the directory from where you launched jupyter notebook.

提交回复
热议问题