'How to load/edit/run/save text files (.py) into an IPython notebook cell?
I've recently moved over to using IPython notebooks as part of my workflow. However, I've not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done?
I've found this in the documentation which tells me how to import .py files as new notebooks but this falls short of what I want to achieve.
Any suggestions would be much appreciated.
Solution 1:[1]
To write/save
%%writefile myfile.py
- write/save cell contents into myfile.py (use
-ato append). Another alias:%%file myfile.py
To run
%run myfile.py
- run myfile.py and output results in the current cell
To load/import
%load myfile.py
- load "import" myfile.py into the current cell
For more magic and help
%lsmagic
- list all the other cool cell magic commands.
%COMMAND-NAME?
- for help on how to use a certain command. i.e.
%run?
Note
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!pythonand%runin the comments below).
Also, see this nbviewer for further explanation with examples. Hope this helps.
Solution 2:[2]
Drag and drop a Python file in the Ipython notebooks "home" notebooks table, click upload. This will create a new notebook with only one cell containing your .py file content
Else copy/paste from your favorite editor ;)
Solution 3:[3]
I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you'll get back the contents of the file, which you can then paste into the cell as code.
Solution 4:[4]
I have not found a satisfying answer for this question, i.e how to load edit, run and save. Overwriting either using %%writefile or %save -f doesn't work well if you want to show incremental changes in git. It would look like you delete all the lines in filename.py and add all new lines, even though you just edit 1 line.
Solution 5:[5]
to write in a file that exists or not use the following
%%writefile script2.py
print(4+5)
print(5+5)
to append to a file use -a argument
%%writefile -a script2.py
print("hello")
when you load the file
%load script2.py
print(4+5)
print(5+5
print("hello")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Raphaƫl Braud |
| Solution 3 | RussellStewart |
| Solution 4 | Quynh Nguyen |
| Solution 5 |
