Skip to content

Instantly share code, notes, and snippets.

@ghego
Created August 22, 2017 15:22
Show Gist options
  • Select an option

  • Save ghego/0e65c3ec0694877f52f4f8c058028021 to your computer and use it in GitHub Desktop.

Select an option

Save ghego/0e65c3ec0694877f52f4f8c058028021 to your computer and use it in GitHub Desktop.
#! $HOME/anaconda/bin/python
# swap $HOME with your absolute path if this doesn't work
import sys
import io
import os
from nbformat import read, write, current_nbformat
from argparse import ArgumentParser
from glob import glob
from shutil import rmtree
def remove_outputs(nb):
for cell in nb.cells:
if cell.cell_type == 'code':
cell.execution_count = None
cell.outputs = []
def process_file(fname, overwrite=False):
with io.open(fname, 'r') as f:
nb = read(f, current_nbformat)
remove_outputs(nb)
if 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)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument("-p", "--path", help="Start directory", type=str, default='**/*.ipynb')
parser.add_argument("-d", "--delete_path", help="Start directory", type=str, default='**/.ipynb_checkpoints')
parser.add_argument("-o", "--overwrite", help="overwrite original file", action="store_true")
args = parser.parse_args()
to_delete = glob(args.delete_path, recursive=True)
for fname in to_delete:
rmtree(fname)
to_clean = glob(args.path, recursive=True)
for fname in to_clean:
process_file(fname, args.overwrite)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment