Skip to content

Instantly share code, notes, and snippets.

@ghego
Forked from damianavila/remove_output.py
Last active August 8, 2017 19:27
Show Gist options
  • Select an option

  • Save ghego/096f352b032608a10d96dffe18696c07 to your computer and use it in GitHub Desktop.

Select an option

Save ghego/096f352b032608a10d96dffe18696c07 to your computer and use it in GitHub Desktop.
Remove output from IPython notebook from the command line (dev version 1.0)
"""
Usage: python remove_output.py notebook.ipynb [-o]
"""
import sys
import io
import os
from nbformat import read, write, current_nbformat
from argparse import ArgumentParser
def remove_outputs(nb):
"""remove the outputs from a notebook"""
for cell in nb.cells:
if cell.cell_type == 'code':
cell.outputs = []
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument("fname", help="Notebook Filename", type=str)
parser.add_argument("-o", "--overwrite", help="overwrite original file", action="store_true")
args = parser.parse_args()
fname = args.fname
with io.open(fname, 'r') as f:
nb = read(f, current_nbformat)
remove_outputs(nb)
if args.overwrite:
new_ipynb = fname
print("Overwriting %s" % new_ipynb)
else:
base, ext = os.path.splitext(fname)
new_ipynb = "%s_removed%s" % (base, ext)
print("New file %s" % new_ipynb)
with io.open(new_ipynb, 'w', encoding='utf8') as f:
write(nb, f, current_nbformat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment