Convert Jupyter(.ipynb) file to Python(.py) file

Am Ma RaH
2 min readOct 25, 2022

--

Photo by AltumCode on Unsplash

While coding, we sometimes need to convert files. In this article, we will explore a magic command to convert a Jupyter(.ipynb) file to Python(.py) file. Several ways are around to do this task, however, our focus is to use a quick and easy method to get the task done.

To instantly convert a .ipynb file to .py file, we need to follow a few steps:

1) Write the entire code (that needs to be converted into a .py file) in a single cell of a Jupyter notebook.

2) Then at the very beginning of the code, in the same cell, write this line of code to convert the file from .ipynb to .py extension.

%%writefile file_name.py

Here, file_name refers to the name of the converted (.py) file.

Example Code:

%%writefile file_name.pydef code_function():
print("We are Coding")

Now, we can find the converted file (file_name.py) in the directory where we currently are.

Moreover, we can also save this file in some specific directory e.g. if we already have the folder_name directory and we want to save the converted file in this directory (folder_name refers to the name of the directory), then we can write

%%writefile folder_name/file_name.py

Conclusion:

In this article, we have gone through a quick and easy way to convert Jupyter (.ipynb) file to Python(.py) file.

In the next article, we will learn how to instantly read Python(.py) files in Jupyter.

Cheers!

--

--

Am Ma RaH

AI Researcher | Software Engineer | Passionate about AI