How to write code files in Jupyter Notebook
Published on Aug. 22, 2023, 12:16 p.m.
To write code files in Jupyter Notebook, you can use the built-in magic command %%writefile
. Here is an example:
%%writefile example.py
def my_function():
print("Hello world!")
In this example, we use the %%writefile
command to write the my_function()
function into a file named example.py
. When you run this cell, the file will be created and the function will be written into it.
Then, you can use import example
in the Notebook to import this module, where example
is the name of the file you wrote the code into. This way, you can call the my_function()
function in the Notebook.
Note that this is not the best way to write code in the Notebook. You can also use code cells to directly write and run the code without writing to a file. But writing to a file can be more convenient if you need to use them in multiple Notebooks or external Python scripts.