简体   繁体   中英

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

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)

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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM