Predictive Hacks

Hack: How to Create files from Jupyter

write file from jupyter

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")

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:


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()

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

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.