Skip to content

Instantly share code, notes, and snippets.

@KoheiKanagu
Last active April 18, 2023 01:20
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save KoheiKanagu/183fdedc486ae5986900c3319bc421c6 to your computer and use it in GitHub Desktop.
Save KoheiKanagu/183fdedc486ae5986900c3319bc421c6 to your computer and use it in GitHub Desktop.
import nbformat
import os
import sys
file_name = sys.argv[1]
def parse(code: list) -> nbformat.v4:
nb = nbformat.v4.new_notebook()
nb["cells"] = []
cell_value = ""
for line in code:
if line.startswith("#%%"):
if cell_value:
nb["cells"].append(nbformat.v4.new_code_cell(cell_value))
cell_value = ""
cell_value += line
if cell_value:
nb["cells"].append(nbformat.v4.new_code_cell(cell_value))
return nb
with open(file_name) as file:
nb = parse(file.readlines())
ipynb = os.path.splitext(os.path.basename(file_name))[0] + ".ipynb"
with open(ipynb, "w") as f:
nbformat.write(nb, f)
print("Generated: ", ipynb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment