__file__ does not exist in Jupyter Notebook

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.


__file__ might not be available for you, but you can get current folder in which your notebook is located in different way, actually.

There are traces in global variables, if you will call globals() you will see that there is an element with the key _dh, that might help you. Here how I managed to load the data.csv file that is located in the same folder as my notebook:

import os

current_folder = globals()['_dh'][0]

# Calculating path to the input data
data_location = os.path.join(current_folder,'data.csv')

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

Jupyter notebook started in ~/dir1/dir2:

Jupyter notebook started in ~/dir1/dir2