Skip to content

Instantly share code, notes, and snippets.

@mathematicalmichael
Forked from damianavila/remove_output.py
Last active September 15, 2022 22:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathematicalmichael/a206b2a21de0bf88a5703e8700403019 to your computer and use it in GitHub Desktop.
Save mathematicalmichael/a206b2a21de0bf88a5703e8700403019 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
Modified from remove_output by Minrk
Modified from remove_output by mathematicalmichael
"""
import sys
import io
import os
from nbformat import read, write, NO_CONVERT
def remove_outputs(nb):
"""remove the outputs from a notebook"""
cell_rm = []
for cell in nb.cells:
cell.outputs = []
nb.metadata.history = []
if __name__ == '__main__':
fname = sys.argv[1]
with io.open(fname, 'r') as f:
nb = read(f, NO_CONVERT)
remove_outputs(nb)
base, ext = os.path.splitext(fname)
new_ipynb = "%s_removed%s" % (base, ext)
with io.open(new_ipynb, 'w', encoding='utf8') as f:
write(nb, f, NO_CONVERT)
print("wrote %s"% new_ipynb)
@mathematicalmichael
Copy link
Author

@emskiphoto seems like the problem is you've got some unhandled character. this snippet seems to work in general but yeah, in no way does it have robust error-handling =/
sorry it didn't work for you, but it sounds like you did the equivalent thing manually. automation like this is really only useful when the problem is persistent. I for one, haven't used it since publication because the underlying problem bloating my notebooks was fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment