How to convert a Jupyter notebook into a Python script ?


Introduction

Jupyter notebooks are a fantastic tool for interactive data analysis, but when it comes to deployment and traditional software development, Python scripts are typically preferred for their simplicity and readability.

This tutorial will guide you through the steps to transform a Jupyter notebook into a standalone Python script.

Converting a Jupyter notebook into a Python script

To convert your Jupyter notebook into a Python script, you have two options. The first option is to navigate to the Jupyter notebook, click on "File," then select "Download as," and choose "Python" from the dropdown menu (as shown in the screenshot below).

How to remove unused modules in a Python script ?
How to remove unused modules in a Python script ?

Alternatively, you can use the following command:

jupyter nbconvert --to python filename.ipynb

Substitute the term "filename" with the name of your Jupyter notebook.

Additional Tips

Optimizing the python file by removing comment lines

When converting your Jupyter notebook into a Python file, you may encounter numerous commented lines like

# In[2]

To remove these lines, you can use the following code:

filename = '/Users/johndoe/Desktop/filename.py'

txt = []
with open(filename, "r") as file:
    for line in file:
        if line.startswith('#'):
            continue
        #line = line.strip()
        txt.append(line)


#print(txt)
print(''.join(txt))

Removing lines that contain line breaks

Additionally, we can also remove lines that contain line breaks

filename = '/Users/johndoe/Desktop/filename.py'

txt = []
with open(filename, "r") as file:
    for line in file:
        if line.startswith('#'):
            continue
        if len(txt)>0 and line == txt[-1]:
            continue
        #line = line.strip()
        txt.append(line)


#print(txt)
print(''.join(txt))

References

Links Site
nbconvert nbconvert.readthedocs.io
Image

of