still_learning
still_learning

Reputation: 806

How can I download (save) all the codes from Jupyter Notebook?

I have written many programs in Jupyter Notebook. I have been downloading manually in HTML and python format. I would like to ask if there is a faster way to download all the programs that I have written there in a folder.

Many thanks

Upvotes: 4

Views: 7806

Answers (4)

Yam Mesicka
Yam Mesicka

Reputation: 6581

Jupyter notebook is a JSON file.

You can open it as a textual file and save all cells which have a code as the cell_type.

import json


PATH_TO_NOTEBOOK = r"/home/yam/notebook.ipynb"


def get_notebook(notebook_path):
    with open(notebook_path, 'r', encoding='utf-8') as notebook:
        return json.load(notebook)


def is_code_cell(cell):
    return cell['cell_type'] == "code"


def get_source_from_code_cell(cell):
    return ''.join(cell['source'])


def save_as_python_file(filename, code):
    with open(f'{filename}.py', 'w', encoding='utf-8') as f:
        f.write(code)


def get_code_cells_content(notebook_cells):
    yield from (
        (i, get_source_from_code_cell(current_cell))
        for i, current_cell in enumerate(notebook_cells, 1)
        if is_code_cell(current_cell)
    )


notebook = get_notebook(PATH_TO_NOTEBOOK)
for filename, code in get_code_cells_content(notebook['cells']):
    save_as_python_file(filename, code)

Upvotes: 2

towhid
towhid

Reputation: 3278

You can do it pretty easily from the notebooks file menu.

Upvotes: 2

pykam
pykam

Reputation: 1481

Jupyter notebooks are saved as .ipynb (ipython notebooks) in your local directory from where you initialise jupyter.

If you just want to save your code for the purposes of looking it up later you can save the notebooks as PDFs.

Try this

jupyter nbconvert path/to/your/ipynb --to=pdf --TemplateExporter.exclude_input=True

Upvotes: 0

Ransaka Ravihara
Ransaka Ravihara

Reputation: 1994

Try this out.

  1. Go to your working directory
  2. Run this command in cmd $ ipython nbconvert --to FORMAT notebook.ipynb.This will convert the IPython document file notebook.ipynb into the output format given by the FORMAT string.

The default output format is HTML, for which the --to the argument may be omitted:

Which mean is if you run ipython nbconvert notebook.ipynb then your notebook.ipynb will convert into HTML file.

$ ls
notebook.ipynb   notebook.html    notebook_files/

Upvotes: 1

Related Questions