Skip to content

Instantly share code, notes, and snippets.

@gabraganca
Forked from damianavila/remove_output.py
Last active December 31, 2023 23:08
Show Gist options
  • Save gabraganca/1dabda659f059f72ba2d to your computer and use it in GitHub Desktop.
Save gabraganca/1dabda659f059f72ba2d to your computer and use it in GitHub Desktop.
"""
Usage: python remove_output.py notebook.ipynb [ > without_output.ipynb ]
Modified from remove_output by Minrk
"""
import sys
import io
import os
import argparse
from IPython.nbformat.current import read, write
def remove_outputs(notebook):
"""remove the outputs from a notebook"""
for ws in notebook.worksheets:
for cell in ws.cells:
if cell.cell_type == 'code':
cell.outputs = []
def read_notebook(ipynb_name):
"""Read a notebook"""
with io.open(ipynb_name, 'r') as f:
notebook = read(f, 'json')
return notebook
def write_notebook(notebook, out_ipynb):
"""write notebook to file"""
with io.open(out_ipynb, 'w', encoding='utf8') as f:
write(notebook, f, 'json')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Remove output cells of " +\
"IPython Notebooks.")
parser.add_argument("notebook", nargs="+",
help="The Ipython Notebook to be cleared.")
parser.add_argument("-o", "--output",
dest="output_filename",
help="write to FILE. If not set, it will rewrite.",
metavar="FILE")
args = parser.parse_args()
if len(args.notebook) == 1:
fname = args.notebook[0]
nb = read_notebook(fname)
remove_outputs(nb)
try:
new_ipynb = os.path.splitext(args.output_filename)[0] + '.ipynb'
except AttributeError:
new_ipynb = fname
write_notebook(nb, new_ipynb)
print "wrote %s" % new_ipynb
elif len(args.notebook) > 1:
for fname in args.notebook:
nb = read_notebook(fname)
remove_outputs(nb)
write_notebook(nb, fname)
print "wrote %s" % fname
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment