Update:
I found this answer which solves the problem. The following command returns the folder path for both *.py and *.ipynb files.
import os
os.path.abspath("")
I have a bit of a work around to solve this issue but I find that it is often helpful to have for non-notebook projects as well. In the same folder as your notebook create a file called "base_fns.py". Inside this file place the following code:
import os
def get_local_folder():
return os.path.dirname(os.path.realpath(__file__))
Then, you can get the path to the folder containing base_fns using:
from base_fns import get_local_folder()
rt_fldr = get_local_folder()
print(rt_fldr)
A few notes:
- This gives you the absolute path to the folder containing "base_fns.py", not your notebook. If your notebook and base_fns are in the same folder, then the absolute path to the folder for your notebook and base_fns will be the same.
- If you place base_fns in a different folder, you will need to know the relative path to navigate from the base_fns folder to your notebook folder.
- If you are working on a larger project with a folder structure, you can place base_fns.py in a known folder and then navigate around to find any other folders/files that you may require.