6

My folder structure is set out like this:

- project/
  - notebooks/
    - notebook1.ipynb
  - src/
    - module1.py
    - __init__.py
  - data/
    - data.csv

Such that I can separate my source code from the actual analysis. I would like to be able to import modules from src and use them in notebook1, however whenever I open notebook1, Jupyter decides to change my working directory to be inside notebooks.

This makes my imports harder to maintain as I'd have to import things relatively to Jupyter's whim - is there any way I can fix the cwd such that it is always project, no matter what file I have open?

I have looked through the docs and my ~/.jupyter/jupyter_notebook_config.py, file but have found nothing that could help me.

EDIT: I'd like to not have to use os.chdir or cd at the top of every script.

Thanks for any help

Akhil Nair
  • 3,144
  • 1
  • 17
  • 32
  • so `c.NotebookApp.notebook_dir = ''` from the config file doesn't do what you want? – Tadhg McDonald-Jensen Mar 27 '17 at 16:31
  • That just changes the directory that the server loads into. With the structure above, it would load jupyter in the `notebooks` directory, so I'd still have to go up a level to get at `src`. – Akhil Nair Mar 27 '17 at 16:42
  • If you are using VSCode with the jupyte extension, there is a setting for this https://stackoverflow.com/a/65683620/4050510 – LudvigH Feb 24 '21 at 08:04

1 Answers1

0

First of all, I think you mean cwd, pwd is the shorthand for print working directory, whereas cwd is the shorthand for current working directory. Essentially, the pwd prints the cwd. Just a minor terminology issue there!

Secondly, you could always manually change the directory yourself at the top of the notebook:

import os
os.chdir("../")  # or manually specify project - whichever you prefer

I don't think there's any way to change the default behaviour automatically though - perhaps opening an issue on the notebook git repo would be a good idea? https://github.com/jupyter/notebook

Louise Davies
  • 14,781
  • 6
  • 38
  • 41
  • Hah thanks for the `pwd` comment. I'd got that from some incorrect lecture [notes](!) that stated it was "Present working directory" - will amend. Regarding the actual answer, this is similar to my back up which was just to use the magic `cd` which works without any imports, but it's still not as neat as I'd like. I'll open an issue. – Akhil Nair Mar 27 '17 at 16:22