Skip to content

Instantly share code, notes, and snippets.

@smartm13
Created January 23, 2019 10:21
Show Gist options
  • Save smartm13/a0c2f612f44ff224d74825a95cc829b9 to your computer and use it in GitHub Desktop.
Save smartm13/a0c2f612f44ff224d74825a95cc829b9 to your computer and use it in GitHub Desktop.
A python module trying to convert jupyter exported .py files back to .ipynb
def py2ipy(fpy):
import nbformat
import re
from nbformat.v4 import new_notebook, new_code_cell
with open(fpy) as f:
src = f.read()
src = src.replace('# coding: utf-8', '')
cells = [new_code_cell(cell) for cell in re.split('\n\n\n# In\[[0-9]+\]:\n\n\n', src)]
cells.pop(0)
nb = new_notebook(cells=cells)
nbformat.write(nb, fpy+'.ipynb')
return fpy+'.ipynb'
if __name__=='__main__':
import sys
if len(sys.argv)<=1:
print("Usage: python -m py2ipynb <exported .py filepath> [-quiet]")
exit()
fpy=sys.argv[1]
op=py2ipy(fpy)
if len(sys.argv)==3 and sys.argv[2].lower().startswith("-q"):pass
else:print(op)
@smartm13
Copy link
Author

To use it frequently, I have saved it inside Lib directory of python anaconda build.
For me it was at: "C:\Users\mihir.parikh\Local_Continuum_Anaconda3\Lib\py2ipynb.py"

@smartm13
Copy link
Author

smartm13 commented Jan 23, 2019

To use it:
Call it from anywhere:
python -m py2ipynb path/to/exported/py/file.py
It will print the resultant notebook path.
To avoid the print send a -quiet or -q after the pyfilepath argument.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment