Skip to content

Instantly share code, notes, and snippets.

@ttor
Created September 29, 2017 10:18
Show Gist options
  • Save ttor/e9f76e75fa8cbada82d9a511e211192c to your computer and use it in GitHub Desktop.
Save ttor/e9f76e75fa8cbada82d9a511e211192c to your computer and use it in GitHub Desktop.
Convert .py with cells (e.g., from Hydrogen) to .ipynb
from nbformat import v3, v4
import sys
import os
infilename=sys.argv[1]
outfilename=os.path.splitext(infilename)[0]+".ipynb"
with open(infilename) as fpin:
text = fpin.read()
text=text.replace("#%%", "# <codecell>")
text=text.replace("# %%", "# <codecell>")
text=text.replace("#<codecell>", "# <codecell>")
import re
text=re.sub(r'(# <codecell>)(.*)(\n)', r'# <markdowncell>\n# #### \2\n# <codecell>\n', text)
nbook = v3.reads_py(text)
nbook = v4.upgrade(nbook)
jsonform = v4.writes(nbook) + "\n"
with open(outfilename, "w") as fpout:
fpout.write(jsonform)
@Madhu94
Copy link

Madhu94 commented Oct 7, 2017

@ttor This is neat !

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