In this short guide, I'll show you how to add, execute or save code from text file or .py files in Python to Jupyter Notebook cells.

We will use Jupyter magics like:

  • %run solution.py
  • %load solution.py
  • %%writefile solution.py

To find more Jupyter magics you can use the command: %lsmagic. Help for specific Jupyter magics by %load?

1. Load code from file in JupyterLab

To load code from Python or text file (i.e. .py - Python code file) we can use function magic:

%load solution.py

This will load the the full content of that file to the JupyterLab cell.

2. Load few lines from file in JupyterLab

To load only few lines from a given file we can use -r parameter:

%load -r 2:4 solution1.py

this will add only lines 2 and 3 to the current cell. It will also comment out the %load -r 2:4 solution1.py itself.

3. Write to a file with JupyterLab cell

We can use magic writefile to write to a file from Jupyter Notebook or lab.

So to add information to file which exists or not can be done from Jupyter cell by:

`%%writefile solution.py`

4. Append to a file from JupyterLab cell

To append to existing text file from Jupyter Notebook cell we can use parameter -a:

%%writefile -a solution.py

5. Run .py file and append results

Finally to run code from another file in Jupyter Notebook or JupyterLab we can use function run:

%run solution.py

This would run solution.py and display the results in the current cell.

Another way to run code from another Python files in JupyterLab is by using !python:

!python solution.py