I recently developed a Jupyter notebook and needed to convert it to a Python script quickly. Unfortunately, the File -> Download as -> Python (.py) option didn't work.
This script will open a Jupyter notebook and convert it to a script:
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
# Convert a Jupyter notebook to a Python script | |
import json | |
# Input file | |
jupyter_filepath = r"my notebook.ipynb" | |
# Output file | |
script_filepath = r"script.py" | |
# Read the Jupyter notebook | |
with open(filepath) as f: | |
data = json.load(f) | |
# Build the lines of the script | |
code = [] | |
for cell in data["cells"]: | |
if cell["cell_type"] == "code": | |
code.extend(cell["source"]) | |
code.append("\n\n") | |
elif cell["cell_type"] == "markdown": | |
markdown = ["# " + content for content in cell["source"]] | |
code.extend(markdown) | |
code.append("\n\n") | |
# Write the script to file | |
with open(script_filepath, 'w') as fp: | |
for line in code: | |
fp.write(line) |
Comments