Last active
April 18, 2023 01:20
-
-
Save KoheiKanagu/183fdedc486ae5986900c3319bc421c6 to your computer and use it in GitHub Desktop.
pyからipynbに変換する http://qiita.com/KoheiKanagu/items/bd2560661f150cf532af
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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