Skip to content Skip to sidebar Skip to footer

Import .py Flie Into Jupyter Notebook Line By Line

I prefer to write my python code on VSCode because of its intellisense and autocomplete features. But I would rather see and debug the code on a Jupyter notebook to better visualiz

Solution 1:

AFAIK, there is no way to do this upon loading your file into a Jupyter notebook. However, you can easily split your big cell into multiple cells, by using ctrl+shift+-. This will split your cell at the position where your cursor is located at that time.

I don't know how big your files are, but it is a really fast and efficient way to split cells so maybe that works for you =)

Solution 2:

You can create a new Jupyter notebook file programmatically with nbformat module. Let me demonstrate all the steps with a working code.

Below are cells in a Jupyter notebook. This cell has a magic command that creates a file, named script001.py.

%%writefile script001.py
x = 10
print('x is: %s' % x)
y = 20
print('y is: %s' % y)
z = x+y
print('z is: %s' % z)

Code in the second cell below creates a new notebook, named split_cells.ipynb.

import nbformat as nbf

# create notebook object
nb2 = nbf.v4.new_notebook()

# prep cells' content for the new notebook
code = []
withopen('script001.py') as fi:
    for aline in fi:
        code.append(aline.rstrip())

# take each line of code as single cells
nb2['cells'] = [nbf.v4.new_code_cell(ea) for ea in code]

# name of notebook to create
fname = 'split_cells.ipynb'# create new notebook filewithopen(fname, 'w') as fj:
    nbf.write(nb2, fj)

When you open the new notebook, split_cells.ipynb, you will have the cells like this:

In[]: x = 10

In[]: print('x is: %s' % x)

In[]: y = 20

In[]: print('y is: %s' % y)

In[]: z = x+y

In[]: print('z is: %s' % z)

This notebook is ready to run as you wish. Hope it helps.

Post a Comment for "Import .py Flie Into Jupyter Notebook Line By Line"