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

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

ai copywriting
Miscellaneous

How AI Transforms Copywriting

Artificial intelligence can be used to empower human copywriters to deliver results. What if marketers could leverage artificial intelligence for