Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save connerxyz/df8e1a2d3915aade869c968725c15cf3 to your computer and use it in GitHub Desktop.
Save connerxyz/df8e1a2d3915aade869c968725c15cf3 to your computer and use it in GitHub Desktop.
Using nbconvert.writers.FilesWriter to convert a Jupyter Notebook to Markdown so that figures *and* the markdown file are output together in an arbitrary directory.
"""
Imagine you have several Jupyter notebooks containing figure you would like to convert to Markdown.
# Using the notebook server:
If you use File->Download as Markdown you get:
Downloads/
notebook.zip
Where the zip contains:
notebook/
notebook.md
output1.png
...
# Using the command-line:
If you use `nbconvert --to markdown ...` on the command line you get:
output-dir/
notebook.md
notebook_files/
output1.png
...
# How do we get a similar behavior when using nbconvert as a library?
The above solutions are nice because they isolate the .md output and its figures together somewhat and properly
specify the figure links in the .md file, but they aren't great when converting a lot of notebooks and/or when
you want to do it programmatically.
## The default behavior:
By default the user is responsible for writing the `output` and `resources` returned by the `MarkdownExporter`.
This is where `FilesWriter` comes in.
By default `FilesWriter` will write the `output` and `resources` to the current working directory.
Configuring a `build_directory` to specify where the `output` and `resources` end up is illustrated below.
This will give you:
whatever/output/path/you/desire/
whatever-notebook-name-you-desire.md
output1.png
...
"""
import nbformat
from nbconvert import MarkdownExporter
from nbconvert.writers import FilesWriter
from traitlets.config import Config
# Load a notebook as an nbformat.NotebookNode using its path
nb_path = "path/to/jupyter/notebook.ipynb"
nb_node = nbformat.read(nb_path, nbformat.NO_CONVERT)
# Employ the nbconvert.MarkdownExporter to obtain output and resources
me = MarkdownExporter()
(output, resource) = me.from_notebook_node(nb_node)
# Employ nbconvert.writers.FilesWriter to write the markdown file
c = Config()
c.FilesWriter.build_directory = "whatever/output/path/you/desire/"
fw = FilesWriter(config=c)
fw.write(output, resources, notebook_name="whatever-notebook-name-you-desire")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment