__file__ does not exist in Jupyter Notebook

前端 未结 4 2057
无人及你
无人及你 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:02

    In modern Python (v3.4+) we can use pathlib to get the notebook's directory:

    from pathlib import Path
    
    cwd = Path().resolve()
    # cwd == PosixPath('/path/to/this/jupyter/ipynb/file's/directory/')
    
    # or this way, thanks @NunoAndré:
    cwd = Path.cwd()
    # cwd == PosixPath('/path/to/this/jupyter/ipynb/file's/directory/')
    



    Update

    @ShitalShah I cannot reproduce the error you are reporting. Jupyter notebook seems to work fine, regardless of the current working directory the application was started.

    Example: file ~/dir1/dir2/untitled.ipynb and Jupyter notebook started in ~/dir1:

    Jupyter notebook started in ~/dir1/dir2:

提交回复
热议问题