Skip to content

Instantly share code, notes, and snippets.

@ddelange
Created November 20, 2019 10:15
Show Gist options
  • Save ddelange/0902f980984246c152095c1309638d35 to your computer and use it in GitHub Desktop.
Save ddelange/0902f980984246c152095c1309638d35 to your computer and use it in GitHub Desktop.
Convert iPython Notebook (.ipynb) to a Python file (.py) from CLI
"""Convert ipynb file to py file from CLI.
Usage:
python ./convert_ipynb_to_py.py [full input path] [full output path]
!! overwrites output path without warning if it exists !!
"""
import sys
import json
with open(sys.argv[1], "r") as f: # input.ipynb
j = json.load(f)
with open(sys.argv[2], "w") as of: # output.py
cells = j["cells"] if j["nbformat"] >= 4 else j["worksheets"][0]["cells"]
for i, cell in enumerate(cells):
of.write("\n# cell " + str(i) + "\n")
for line in cell["source"]:
of.write(line)
of.write("\n\n")
@Sopwith
Copy link

Sopwith commented Oct 11, 2024

Thanks for this.

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