How to load/edit/run/save text files (.py) into an IPython notebook cell?
EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.
A text file can be loaded in a notebook cell with the magic command
If you execute a cell containing:
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. Beware that if a file with the same name already exists it will be silently overwritten.
To see the help for any magic command add a
For general help on magic functions type "%magic"For a list of the available magic functions, use %lsmagic. For a descriptionof any of them, type %magic_name?, e.g. '%cd?'.
See also: Magic functions from the official IPython docs.
- write/save cell contents into myfile.py (use
-ato append). Another alias:
- run myfile.py and output results in the current cell
- load "import" myfile.py into the current cell
For more magic and help
- list all the other cool cell magic commands.
- for help on how to use a certain command. i.e.
Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the
%%bash cell magic command).
To run a unix command from the cell, just precede your command with
! mark. for example:
!python --versionsee your python version
!python myfile.pyrun myfile.py and output results in the current cell, just like
%run(see the difference between
%runin the comments below).
Also, see this nbviewer for further explanation with examples.Hope this helps.