IPython Notebook comes with nbconvert, which can export notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already ha
Some improvement to @p-toccaceli answer. Now, it also restores markdown cells. Additionally, it trims empty hanging lines for each cell.
import nbformat
from nbformat.v4 import new_code_cell,new_markdown_cell,new_notebook
import codecs
sourceFile = "changeMe.py" # <<<< change
destFile = "changeMe.ipynb" # <<<< change
def parsePy(fn):
""" Generator that parses a .py file exported from a IPython notebook and
extracts code cells (whatever is between occurrences of "In[*]:").
Returns a string containing one or more lines
"""
with open(fn,"r") as f:
lines = []
for l in f:
l1 = l.strip()
if l1.startswith('# In[') and l1.endswith(']:') and lines:
yield ("".join(lines).strip(), 0)
lines = []
continue
elif l1.startswith('# ') and l1[2:].startswith('#') and lines:
yield ("".join(lines).strip(), 0)
yield (l1[2:].strip(), 1)
lines = []
continue
lines.append(l)
if lines:
yield ("".join(lines).strip(), 0)
# Create the code cells by parsing the file in input
cells = []
for c, code in parsePy(sourceFile):
if len(c) == 0:
continue
if code == 0:
cells.append(new_code_cell(source=c))
elif code == 1:
cells.append(new_markdown_cell(source=c))
# This creates a V4 Notebook with the code cells extracted above
nb0 = new_notebook(cells=cells,
metadata={'language': 'python',})
with codecs.open(destFile, encoding='utf-8', mode='w') as f:
nbformat.write(nb0, f, 4)