Hack: How to Create files from Jupyter

[This article was first published on Python – Predictive Hacks, and kindly contributed to python-bloggers]. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

Sometimes, while working with the Jupyter notebook you need to create a file, like a .py file. Today we will show how to create files within Jupyter using the magic cells.

Write files from Jupyter

We can simply type %%writefile myfile within a Jupyter cell and then start writing the file. For example:

%%writefile myfile.py

def my_function():
    print("Hello from a function")
Hack: How to Create files from Jupyter 1

will create a new file called myfile.py

If we want to see the content of the file we can type !cat myfile.py and we get:

Hack: How to Create files from Jupyter 2

Append files from Jupyter

Now, let’s say that we want to add something to our file. We can use the parameter -a which comes from the append.

For example, if we want to add the my_function() to our file:

%%writefile -a myfile.py

my_function()
Hack: How to Create files from Jupyter 3

As we can see, we added the my_function() to the myfile.py

Run the Script from Jupyter

We can simply use the command !python myfile.py or alternatively to type %run -i myfile.py

Hack: How to Create files from Jupyter 4
To leave a comment for the author, please follow the link and comment on their blog: Python – Predictive Hacks.

Want to share your content on python-bloggers? click here.