Run from and save to .py file from Jupyter Notebook

A text file can be loaded in a notebook cell with the magic command %load.

If you execute a cell containing:

%loadpy filename.py


The content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

To save the cell content back into a file add the cell-magic
%%writefile filename.py
at the beginning of the cell and run it.

To see the help for any magic command add a ?: like %loadpy? or %%writefile?.
%COMMAND-NAME?
i.e. %run?

For list of available magic function use %lsmagic. Alternatively there is also another method magic function called %save-f but I would not recommend that, it's an indirect way of saving files.

Also see -
1. Magic Functions docs
2.this nbviewer for further explanation with examples.

Hope this helps.


This is not the exact answer. At one point, I was able to open .py files using python notebook and work on it as if it were a notebook file.

However, I have been able to replicate this behavior using VScode.

https://code.visualstudio.com/docs/python/jupyter-support-py

Using VScode, you can export all your .ipynb files into .py files, then run code blocks. Code blocks are separated by # %%.

I have not used it sufficiently long enough to decide if it is better than python notebook, but this seems to be the best solution so far. I previously tried using Atom/Hydrogen and did not enjoy the experience.