Reputation: 806
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
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
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
Reputation: 1994
Try this out.
$ 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